简体   繁体   中英

Asp.net Web Api Identity send bearer token in all request

I've a Web Api App with Identity 2 security. 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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM