Asp.net Web Api Identity在所有请求中发送承载令牌

问题描述 投票:0回答:1

我有一个带有Identity 2安全性的Web Api App。我可以登录并获得带有持票人令牌的回复

{"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个回答
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")
    }

祝好运

© www.soinside.com 2019 - 2024. All rights reserved.