Search code examples
apispring-securityasp.net-mvc-5

Heasers needed by spring security to consume api


I developped an api using spring boot withuser authentication and authorizations with spring securtiy. And I am using spring security login form for user authentication. I tested it with postman and it is working perfectly.

But when I implemented the api in asp.net mvc 5 project the login works and return the connected user but i get unauthorized message after any other request that needs authenticated user.

I think it works in postman because he generates or get headers from response of login.

How can i get them so i can integrate them in other requests.

Edit: It seems that JSESSIONID Cookie header is needed and I took it from login response header and added it to my request header but it still doesn't work

Here is my code that adds the header:

HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Add("Cookie", loginResponse.Headers.GetValues("Set-Cookie").First().Split(';')[0].Trim());
client.DefaultRequestHeaders.Add("Cache-Control", "no-cache");
client.BaseAddress = new Uri("http://localhost:8080/api/");
HttpResponseMessage response = client.GetAsync("customer/users").Result;

This line give me the Cookie header value from login response i need:

loginResponse.Headers.GetValues("Set-Cookie").First().Split(';')[0].Trim()

Solution

  • HttpClient will ignore header Cookie when creating an instance to it you need to pass an HttpClientHandler with UseCookies to false so it will not ignore it

    HttpClient httpClient = new HttpClient(new HttpClientHandler { UseCookies = false })
    

    Answer found here