Java – licensed using rolesalloweddynamicfeature and Jersey
I'm trying to authenticate users using Jax - RS filters This is the filter I am setting up for the new securitycontext:
@Provider public class AuthenticationFilter implements ContainerRequestFilter { @Override public void filter(final ContainerRequestContext requestContext) throws IOException { requestContext.setSecurityContext(new SecurityContext() { @Override public Principal getUserPrincipal() { return new Principal() { @Override public String getName() { return "Joe"; } }; } @Override public boolean isUserInRole(String string) { return false; } @Override public boolean isSecure() { return requestContext.getSecurityContext().isSecure(); } @Override public String getAuthenticationScheme() { return requestContext.getSecurityContext().getAuthenticationScheme(); } }); if (!isAuthenticated(requestContext)) { requestContext.abortWith( Response.status(Status.UNAUTHORIZED) .header(HttpHeaders.WWW_AUTHENTICATE,"Basic realm=\"Example\"") .entity("Login required.").build()); } } private boolean isAuthenticated(final ContainerRequestContext requestContext) { return requestContext.getHeaderString("authorization") != null; // simplified } }
The resource method is as follows:
@GET // @RolesAllowed("user") public Viewable get(@Context SecurityContext context) { System.out.println(context.getUserPrincipal().getName()); System.out.println(context.isUserInRole("user")); return new Viewable("index"); }
Rolesalloweddynamicfeature is registered as follows:
.register(RolesAllowedDynamicFeature.class)
I can see the expected output on the console However, if I uncomment @ rolesallowed ("user"), I will receive a forbidden error and will never call the isuserinrole method of securitycontext Following API doc rolesalloweddynamicfeature, this method should be called
How do I use rolesalloweddynamicfeature?
Solution
You need to define the priority for the authentication filter, otherwise the rolesallowedrequestfilter in the rolesalloweddynamicfeature will be executed before the authenticationfilter If you look at the source code, rolesallowedrequestfilter has the comment @ priority (priorities. Authorization), so if you assign @ priority (priorities. Authorization) to your authentication filter, it will be executed before rolesallowedrequestfilter like this:
@Provider @Priority(Priorities.AUTHENTICATION) public class AuthenticationFilter implements ContainerRequestFilter {
You may also need to actually register the authenticationfilter using the register (authenticationfilter. Class), depending on whether your server scans for comments