0
votes

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.

1

1 Answers

1
votes

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