I want to perform authentication in a filter before my resource method is called. Within this filter I would also like to retrieve the permissions of a user and pass it on through a RequestScoped @Inject annotation.
@Authenticated
public class AuthenticationFilter implements ContainerRequestFilter {
@NameBinding
@Retention(RetentionPolicy.RUNTIME)
public @interface Authenticated {};
@Inject
private ISecurityHandler handler;
public AuthenticationFilter() {}
@Override
public void filter(ContainerRequestContext requestContext) throws IOException {
// Filter out unauthorized
// Retrieve user permissions
this.handler.setUserPermissions(...);
}
}
Resource:
@Path("my-path")
public class GetVisitorsDataResource {
@Inject private ISecurityHandler handler;
@GET
@Path("resource-method")
@Authenticated
@Produces(MediaType.APPLICATION_JSON)
public Response resource() {
System.out.println(handler.getUserPermissions());
return Response.ok().build();
}
}
I have registered the filter and a Factory for the injection.
public static class SecurityHandlerProvider implements Factory<ISecurityHandler> {
@Override
public ISecurityHandler provide() {
System.out.println("PROVIDING SECURITY CONTEXT!");
return new SecurityHandlerImpl();
}
@Override
public void dispose(ISecurityHandler instance) {
System.out.println("DISPOSING SECURITY CONTEXT!");
}
}
I have also bound it.
bindFactory(SecurityHandlerProvider.class).to(ISecurityHandler.class).in(RequestScoped.class);
It is important that the object is created when a request is received and only accessible within that request. When the request is finished, the dispose method should be called. The only way I can achieve something similar is through the @Singleton annotation. However, the object is not destroyed after the request is completed and is shared across all requests.
I have been investing too much time into this issue already, is there perhaps anybody that knows how to achieve the preferred result?