spring 安全需要 Heasers 消耗 api

Heasers needed by spring security to consume api

我开发了一个 api 使用 spring boot withuser authentication and authorizations with spring securtiy。 我正在使用 spring 安全登录表单进行用户身份验证。 我用邮递员测试了它,它工作得很好。

但是当我在 asp.net mvc 5 项目中实现 api 时,登录有效并且 return 连接的用户,但是在任何其他需要经过身份验证的用户的请求之后我收到未经授权的消息。

我认为它适用于邮递员,因为他从登录响应中生成或获取 headers。

如何获取它们以便将它们集成到其他请求中。

编辑: 似乎需要 JSESSIONID Cookie header,我从登录响应 header 中获取它并将其添加到我的请求 header 但它仍然不起作用

这是我添加 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;

这一行给我我需要的登录响应中的 Cookie header 值:

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

HttpClient 将忽略 header Cookie 在为其创建实例时,您需要将带有 UseCookies 的 HttpClientHandler 传递给 false,这样它就不会忽略它

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

Answer found here