How to enable CORS in Java projects with JWT implementation?

Asked

Viewed 438 times

-1

I am doing a web service project, where I implemented the JWT and to consume using Reactjs I enabled the CORS, but when I make a request that needs to have the token, this returning it: Access to fetch at 'http://localhost:8080/test/' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn’t pass access control check: It does not have HTTP ok status.

If it is a GET request but does not need the token, it consumes normal.

When using JWT something needs to be done besides creating the filter class (Containerresponsefilter)?

@Provider
public class CORSResponseFilter implements ContainerResponseFilter {
@Override
public void filter(ContainerRequestContext containerRequestContext,
ContainerResponseContext containerResponseContext) throws IOException {
containerResponseContext.getHeaders().add(
"Access-Control-Allow-Origin", "http://localhost:3000");
containerResponseContext.getHeaders().add(
"Access-Control-Allow-Credentials", "true");
containerResponseContext.getHeaders().add(
"Access-Control-Allow-Headers",
"origin, X-Requested-With, content-type, accept, Authorization");
containerResponseContext.getHeaders().add(
"Access-Control-Allow-Methods",
"GET, POST, PUT, DELETE, OPTIONS, HEAD");
}
}

1 answer

0

The error of the browser Response to preflight request doesn't pass access control check: It does not have HTTP ok status indicates the endpoint http://localhost:8080/test/ is not returning the code HTTP 200 OK for the method call HTTP OPTIONS.

Check your application log for errors at this endpoint, fix the errors found and test again.

  • When debugging the web server done in java, I will find that class in Jwtfilter in the snippet; String authorizationHeader = requestContext.getHeaderString(Httpheaders.AUTHORIZATION); This Null, will the problem be in the way I am sending the token?

  • Yes possible. Editing the question, adding the request being sent, will help improve the answer :)

  • Can you cite an example using reactjs please?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.