I am a backend developer and i am providing a spring boot rest API with JWT security to consume for a front end developer who calls the api from local host.So when he calls a POST request he says he gets an CORS error.So I added the part
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
response.setHeader("Access-Control-Allow-Credentials", "true");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "Content-Type, Accept, X-Requested-With, remember-me");
chain.doFilter(request, response);
}
But still he gets the error.What may be the cause.Any help is appreciated
OPTIONS https:my.domain/url 401 (Unauthorized)
when it is a POST request.
Controller code:
@RestController
public class RegistrationController {
@Autowired
@Qualifier("restTemplateUserRegitration")
private RestTemplate restTemplateUserRegitration;
@RequestMapping(value="${user.endpoint}",produces={MediaType.APPLICATION_JSON_VALUE},method=RequestMethod.POST)
public ResponseEntity<?> registerUser(@RequestBody Model ModelRequest){
Map<String, Object> Status=new HashMap<String, Object>();
FeedBackStatus = restTemplateUserRegitration.postForObject("http:serviceurl",registration/single",Model.class,Map.class );
return ResponseEntity.ok(Status);
}
}
I also had a similar experience. We have solved the problem as follows. This code added in securityConfiguration. The browser will send the OPTIONS request first before sending the POST request. Therefore, when the request is sent, the authorization header value is not included in the request header, so the JWT filter judges that the user is unauthenticated.
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring()
.antMatchers(HttpMethod.OPTIONS);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With