3

I have used Tokens to secure my Web API website, and consumed this API from an AngularJS client application.

With this I am able to login with token based authentication. My issue is that I am not able to get the UserId in Web API controller.

Both User.Identity.GetUserId() and RequestContext.Principal.Identity.GetUserId() are returning null.

How to get the UserId in an ApiController?

Brendan Green
  • 11,676
  • 5
  • 44
  • 76
RohitV
  • 65
  • 1
  • 7

1 Answers1

0

If you already have a bearer token, set the Authorization header in javascript.

var token = sessionStorage.getItem(tokenKey);
var headers = {};
if (token) {
    headers.Authorization = 'Bearer ' + token;
}

Then you should include headers in your ajax request:

 $.ajax({
        type: 'GET',
        url: 'api/values/1',
        headers: headers
    }).done(function (data) {
        self.result(data);
    }).fail(showError);

Finally in your controller you can get user id by:

var userId = RequestContext.Principal.Identity.GetUserId();

for more information refer to Secure a Web API with Individual Accounts and Local Login in ASP.NET Web API 2.2