【问题标题】:Asp.net Web Api Identity send bearer token in all requestAsp.net Web Api Identity 在所有请求中发送不记名令牌
【发布时间】:2014-06-19 09:25:44
【问题描述】:

我有一个具有 Identity 2 安全性的 Web Api 应用程序。我可以登录并获得带有不记名令牌的响应,例如

{"access_token":"wiYvAyIgGggCmBBR36VwWZ[more...]",
 "token_type":"bearer","expires_in":1209599,
 "userName":"Ezeqiel",".issued":"Fri, 02 May 2014 15:23:27 GMT",
 ".expires":"Fri, 16 May 2014 15:23:27 GMT" }

问题是如何将此令牌发送到未来的请求,以及如何在用户未通过身份验证时重定向到登录页面。

【问题讨论】:

    标签: asp.net login asp.net-web-api asp.net-identity bearer-token


    【解决方案1】:

    这取决于客户的类型。

    如果是aspnet类型的服务器端,可以放在session/cache/httpcontext中,在httpclient中随每个请求一起发送。

    using (var apiClient = new HttpClient { BaseAddress = new Uri("http://localhost:54744/") })
    {
        var results = apiClient.PostAsJsonAsync("api/Authenticate/Token", loginModel).Result;
        string token = results.Content.ReadAsAsync<string>().Result;
        apiClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
    }
    

    如果它是一个 javascript spa 类型的应用程序,那么在来自 javascript 的登录请求中,您会从服务器返回该令牌,并将其保存在存储或变量中,并在每个 ajax 请求中使用它。

    角度看起来像这样

    config.headers.Authorization = 'Bearer ' + $window.sessionStorage.token;
    

    ajax 看起来像这样

     beforeSend: function (xhr) {
          xhr.setRequestHeader("Authorization", "Bearer $token")
        }
    

    祝你好运

    【讨论】:

      猜你喜欢
      • 2021-07-21
      • 2016-03-06
      • 2020-12-11
      • 2018-01-24
      • 2012-11-16
      • 2021-10-10
      • 2021-08-05
      • 2016-05-12
      • 2019-02-20
      相关资源
      最近更新 更多