问题
I´m using HTTP-Authentication based on my customer-table. After the user is authenticated a restful webservice is called. But how can I access in the webservice the HTTP-Authentication (the Header Data of the HttpRequest)? My code looks like this:
@GET
@Path("{id}")
@Produces({"application/xml"})
public ObjectList read(@PathParam("id") Integer id) {
... //how to get here the HTTP-Username and Password?
}
回答1:
In order to get the Principal
and its role, inject @Context SecurityContext
in the class body or in the method input parameters.
import javax.ws.rs.core;
//
public ObjectList read(
@PathParam("id") Integer id,
@Context SecurityContext sc) {
String principalUserName = sc.getUserPrincipal().getName();
if (sc.isUserInRole("MyRole")) {
return new MyRoleResource();
} else {
return new MyDefaultRoleResource();
}
}
回答2:
Add more parameters to your method like this:
import javax.ws.rs.HeaderParam;
// ...
public ObjectList read(
@PathParam("id") Integer id,
@HeaderParam("user-agent") String userAgent,
@HeaderParam("X-auth-token") String authToken) ...
来源:https://stackoverflow.com/questions/9005124/glassfish-3-1-1-retrieve-http-authentication-in-restful-webservice