Span | ||
---|---|---|
| ||
JAX-RS: Security |
...
It is often containers like Tomcat or frameworks like Spring Security which handle the user authentication. Sometimes you might want to do the custom authentication instead. CXF HTTP Transport adds decoded Basic Authentication credentials into an instance of AuthorizationPolicy extension and sets it on the current message. Thus the easiest way is to register a custom invoker or RequestHandler
or @PreMatching ContainerRequestFilter
filter which will extract a user name and password like this:
Code Block | ||||
---|---|---|---|---|
| ||||
public class AuthenticationHandler implements RequestHandlerContainerRequestFilter { @Override public Responsevoid handleRequestfilter(MessageContainerRequestContext m,requestContext) ClassResourceInfothrows resourceClass)IOException { AuthorizationPolicyString policyauthorization = (AuthorizationPolicy)m.get(AuthorizationPolicy.classrequestContext.getHeaderString("Authorization"); String[] usernameparts = policyauthValues.getUserNameauthorization(" "); String password = policy.getPassword(); if (parts.length != 2 || !"Basic".equals(parts[0])) { if requestContext.abortWith(isAuthenticatedcreateFaultResponse(username, password)); { return; // let request to continue } String decodedValue return= null; } elsetry { // authentication failed, request the authetication, add the realm name if needed to the value of WWW-Authenticate decodedValue = new String(Base64Utility.decode(parts[1])); } catch (Base64Exception ex) { requestContext.abortWith(createFaultResponse()); return; } String[] namePassword = decodedValue.split(":"); if (isAuthenticated(namePassword[0], namePassword[1])) { // let request to continue } else { // authentication failed, request the authetication, add the realm name if needed to the value of WWW-Authenticate context.abortWith(Response.status(401).header("WWW-Authenticate", "Basic").build()); } } private Response createFaultResponse() { return Response.status(401).header("WWW-Authenticate", "Basic realm=\"service.com\"").build(); } } } |
One other thing you may want to do, after authenticating a user, is to initialize org.apache.cxf.security.SecurityContext with Principals representing the user and its roles (if available).
...