有许多方法可以获得REST(简单)服务的良好安全性.我已经试过了.在这种情况下,只需要基本身份验证.所以,不是基于登录,RequestFilters等.请关注这个例子.
在为一个RestEasy’post’方法添加安全性的同时,我继续获得401个异常.如何安全访问“帖子”?我使用了Adam Bien /AtjemKönig的Authenticator代码.
如果没有web.xml中的安全设置,我将获得正常访问,因此部分代码工作正常.
我不需要/想要任何登录屏幕.
Tomcat用户:conf / tomcat-users.xml:
Web.xml文件:
wine secret
/rest/wines/secret
POST
winer
BASIC
winer
申请类:
@ApplicationPath("/rest")
public class RestEasyWineServices extends Application {
}
Authenticator utils:
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import javax.ws.rs.client.ClientRequestContext;
import javax.ws.rs.client.ClientRequestFilter;
import javax.ws.rs.core.MultivaluedMap;
import javax.xml.bind.DatatypeConverter;
public class Authenticator implements ClientRequestFilter {
private final String user;
private final String password;
public Authenticator(String user, String password) {
this.user = user;
this.password = password;
}
public void filter(ClientRequestContext requestContext) throws IOException {
MultivaluedMap headers = requestContext.getHeaders();
final String basicAuthentication = getBasicAuthentication();
headers.add("Authorization", basicAuthentication);
}
private String getBasicAuthentication() {
String token = this.user + ":" + this.password;
try {
return "Basic " +
DatatypeConverter.printBase64Binary(token.getBytes("UTF-8"));
} catch (UnsupportedEncodingException ex) {
throw new IllegalStateException("Cannot encode with UTF-8", ex);
}
}
}
资源类和方法:
@Path("/wines")
public class WineResource {
...
@POST @Path("secret")
@Produces({ MediaType.APPLICATION_JSON })
@Consumes({ MediaType.APPLICATION_JSON})
public Wine echoPostWineSecret( Wine inputWine2) {
System.out.println( "Server: **SECRET** post (" + inputWine2 + ")");
inputWine2 = dao.create(inputWine2);
return inputWine2;
}
}
客户类:
Client clientSecret = ClientBuilder.newClient().register(new Authenticator( "wineuser", "winepass"));
WebTarget targetSecret = clientSecret.target("http://localhost:8080").path("/RestRestEasyJquerySqlite2Hibernate/rest/wines");
wine.setId( 1231);
wine.setName( "secret wine name_" + dateKey);
wine.setCountry( "secret wine country_" + dateKey);
wine.setGrapes( "secret wine grapes_" + dateKey);
wine.setRegion( "secret wine region_" + dateKey);
try {
wine = targetSecret.path( "secret").request( MediaType.APPLICATION_JSON_TYPE).post( Entity.entity( wine, MediaType.APPLICATION_JSON_TYPE), Wine.class);
System.out.println( "SECRET created wine: " + wine);
} catch( Exception e) {
System.out.println( "ERROR: Back on the client: exception");
e.printStackTrace();
}