Angularjs Post not sending headers to Spring JWT

Viewed 1668

I have a web app built by AngularJs and a backend app built by Spring and I'm using JWT to secure my app. With Get method everything is ok, at the backend level I get the bearer token I'm expecting so I can return private information. But with POST method the bearer token is not sent. I don't know if this is an issue from backend or frontend layer. here you have my code:

AngularJS

$http({
        method: 'POST',
        url: SessionService.apiUrl + '/category/create',
        headers: {
          'Accept': 'application/json','Content-Type': 'application/json; 
           charset=UTF-8;', 'Authorization': 'Bearer ' + SessionService.getToken()
       },
        data: params
 })

For GET method I have exactly the same (without params and with method GET) and it is working.

At Backend:

@RequestMapping(value = "/category/create", method = RequestMethod.POST)
    public @ResponseBody
    Response add(@RequestBody CategoryBO request) {
...
}

And to get the Authorization header I'm using io.jsonwebtoken library in the following way:

protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
                                    FilterChain filterChain) throws ServletException, IOException {
        String authorizationHeader = request.getHeader("authorization");

Using Postman the backend is working well, but with angularjs is not.

GET - Request Header:

Accept:application/json, text/plain, */*
Accept-Encoding:gzip, deflate, sdch
Accept-Language:es-ES,es;q=0.8,en;q=0.6,pt;q=0.4
Authorization:Bearer eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJmYWJpYW4uYW5nZWxvbmkiLCJyb2xlcyI6IkFETUlOIiwiaWF0IjoxNDU5MDE5MTg0fQ.QAPZDbyavambfdK9LJUQWyzSRAuELvg_IGTjFdsm6cc
Connection:keep-alive
Host:localhost:8080
Origin:http://localhost:3000
Referer:http://localhost:3000/
User-Agent:Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.87 Safari/537.36

POST - Resquest Header

Accept:*/*
Accept-Encoding:gzip, deflate, sdch
Accept-Language:es-ES,es;q=0.8,en;q=0.6,pt;q=0.4
Access-Control-Request-Headers:accept, authorization, content-type
Access-Control-Request-Method:POST
Connection:keep-alive
Host:localhost:8080
Origin:http://localhost:3000
Referer:http://localhost:3000/
User-Agent:Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.87 Safari/537.36
2 Answers

Thanks @user2858970 for the explanation. I found it very lucid.

To get the issue resolved, you basically need to work with two stuff:

  1. Enable CORS in your server because your server has to know that it is getting request from client which is in different domain.
  2. Enable CORS at Spring Security level as well to allow it to leverage the configuration defined at Spring MVC level.

I've put the explanation along with code to answer CORS with spring-boot and angularjs not working .

Related