Custom @RolesAllowed Roles in Jersey WebService with ContainerRequestFilter

I created a filter with the ContainerRequestFilter interface and tried to assign my own roles that return a custom object.

@Override public ContainerRequest filter(ContainerRequest request) { User user = authenticate(request); if (user != null) { request.setSecurityContext(new Authorizer(user)); } else { throw new WebApplicationException(400); } return request; } private User authenticate(ContainerRequest request) { user = new User("erhan", "customRole"); return user; } public class Authorizer implements SecurityContext { private User user; private Principal principal; public Authorizer(final User user) { this.user = user; this.principal = new Principal() { public String getName() { return user.username; } }; } public Principal getUserPrincipal() { return this.principal; } public boolean isUserInRole(String role) { return (role.equals(user.role)); } public boolean isSecure() { return "https".equals(uriInfo.getRequestUri().getScheme()); } public String getAuthenticationScheme() { return SecurityContext.BASIC_AUTH; } } public class User { public String username; public String role; public User(String username, String role) { this.username = username; this.role = role; } } 

Everything is fine with this filter, but when it goes to the web service

  @GET @RolesAllowed({"customRole"}) @Path("/test") public String getByType(@Context HttpHeaders headers,@Context SecurityContext sc, @Context HttpServletRequest request) { return null; } 

it reaches the web service, but when I change the role, I still get to the same web service. How can I provide various custom roles in Jersey?

+4
source share
2 answers

Using Jersey 2, you can simply register RolesAllowedDynamicFeature and protect your application in web.xml . What you do not need the implementation of SecurityContext .

For more information, see the Custom Custom SecurityContext on the jax-rs EJB resource .

+2
source

Try annotating the class. Added @PreMatching to me with @Provider for me . It seems that in this case the mandatory annotation of the provider is mandatory.

 @PreMatching @Provider public class RequestFilter implements ContainerRequestFilter { ..... } 

If this does not work, try adding this: @Priority (Priorities.AUTHORIZATION)

Additionally, you need to enable roles and register RolesAllowedDynamicFeature or use alternatives - test example 19.2

0
source

Source: https://habr.com/ru/post/1400090/


All Articles