Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I allow cross origin request

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); 
    }
}
like image 585
joker21 Avatar asked Nov 18 '22 04:11

joker21


1 Answers

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);
}
like image 101
Anselm Kim Avatar answered Jan 10 '23 19:01

Anselm Kim