I am trying to fix my JAX RS API here.
I use Java 8 Security API (with Jersey 2) for authentication with JWT through my JWTAuthenticationMechanism
class which is represented below.
public class JWTAuthenticationMechanism implements HttpAuthenticationMechanism {
@Override
public AuthenticationStatus validateRequest(HttpServletRequest request, HttpServletResponse response, HttpMessageContext context) {
if (ok) {
return context.notifyContainerAboutLogin(..., ...);
else {
return context.responseUnauthorized();
}
}
}
And I also use CORSFilter
to enable CORS on my server.
@Provider
public class CORSFilter implements ContainerResponseFilter {
@Override
public void filter(ContainerRequestContext req, ContainerResponseContext res) throws IOException {
res.getHeaders().add("Access-Control-Allow-Origin", "*");
res.getHeaders().add("Access-Control-Allow-Headers", "origin, content-type, accept, authorization");
res.getHeaders().add("Access-Control-Allow-Credentials", "true");
res.getHeaders().add("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, HEAD");
}
}
My problem is that when JWTAuthenticationMechanism
do context.responseUnauthorized()
, it responds directly to the client without passing through my CORSFilter
.
Then, client receives CORS error instead of a HTTP 401 Unauthorized.
Everything looks fine when I add manually CORS headers before using responseUnauthorized
, so responseUnauthorized
is really bypassing the filter.
context.getResponse().addHeader("Access-Control-Allow-Origin", "*");
context.getResponse().addHeader("Access-Control-Allow-Headers", "origin, content-type, accept, authorization");
context.getResponse().addHeader("Access-Control-Allow-Headers", "origin, content-type, accept, authorization");
context.getResponse().addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, HEAD");
return context.responseUnauthorized();
Any idea ?