【问题标题】:Heasers needed by spring security to consume apiSpring Security 消耗 api 所需的 Heasers
【发布时间】:2021-07-06 18:51:54
【问题描述】:

我使用带有用户身份验证和授权的 Spring Boot 开发了一个 API。 我正在使用 Spring Security 登录表单进行用户身份验证。 我用邮递员测试了它,它工作得很好。

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

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

我怎样才能得到它们,以便将它们集成到其他请求中。

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

这是我添加标题的代码:

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 标头值:

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

【问题讨论】:

    标签: api spring-security asp.net-mvc-5


    【解决方案1】:

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

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

    Answer found here

    【讨论】:

      猜你喜欢
      • 2019-08-22
      • 2022-08-16
      • 2020-11-23
      • 2015-07-04
      • 2011-08-17
      • 2023-03-28
      • 1970-01-01
      • 2023-01-07
      • 2011-04-19
      相关资源
      最近更新 更多