[英]Asp.net Web Api Identity send bearer token in all request
I've a Web Api App with Identity 2 security. 我有一个具有Identity 2安全性的Web Api应用程序。 I can Login and get a response with bearer token like
我可以登录并获得带有承载令牌的响应,例如
{"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" }
The question is how can send this token to future request and how can redirect to login page when the user is not authenticated. 问题是当用户未通过身份验证时,如何将该令牌发送到将来的请求,以及如何重定向到登录页面。
It depends on the type of client. 这取决于客户端的类型。
If its a aspnet type server side, you can put it in session/cache/httpcontext and send it with each request in the httpclient. 如果它是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);
}
If its a javascript spa type app, then on your login request from javascript you return that token from the server and you save it in storage or a variable and use it on each ajax request. 如果它是一个javascript spa类型的应用程序,则从javascript登录请求时,您将从服务器返回该令牌,然后将其保存在存储或变量中,并在每个ajax请求中使用它。
angular looks something like this 角看起来像这样
config.headers.Authorization = 'Bearer ' + $window.sessionStorage.token;
ajax looks something like this 阿贾克斯看起来像这样
beforeSend: function (xhr) {
xhr.setRequestHeader("Authorization", "Bearer $token")
}
Good luck 祝好运
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.