Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

User.Identity.GetUserId() method not working in a Web Api 2 Controller

In a regular controller the following code works:

[HttpPost]
public ActionResult Custom()
{
    string name = User.Identity.GetUserName();
    string id = User.Identity.GetUserId();
    return Content(string.Format("Name:{0} </br> ID: {1}",name, id));
}

In a Web Api 2 Controller the name and id strings are empty:

[HttpPost]
public IHttpActionResult Test()
{
    string name = User.Identity.GetUserName();
    string id = User.Identity.GetUserId();
    return Ok();
}

Can anyone tell me why GetUserId() works in a normal controller but not in an Api? In both cases i am logged in, and GlobalConfiguration.Configure(WebApiConfig.Register);is added in Application_Start() in Global.asax.cs.

And i have another problem. If i decorate my api controller with [Authorize] attribute, I can't even access my api. The Postman will direct me to the Login page, when a I am already logged in.

[[Authorize]]
public class TestController : ApiController
{
    ....
like image 855
Alexe Barlescu Avatar asked Oct 18 '22 05:10

Alexe Barlescu


2 Answers

NKosi was correct. This problem had me stumped for a while until I read his comment.

If your situation is just like my case then you need to set the Bearer token for all authenticated requests to the WebAPI Controller. The MVC controllers use cookie authentication, which is set up already separately and works. But for the WebAPI controllers, apparently we have to do a little more legwork.

In my default "Individual User Accounts" WebAPI project I see that a session storage variable, 'accessToken', is already set by default. All I had to do was read it from that session storage variable and make sure that every request from my client to the WebAPI controller had the 'Authorization' header set to 'Bearer [your authentication token]'.

From, http://www.asp.net/web-api/overview/security/individual-accounts-in-web-api, this is what the 'Get' request to the WebAPI controller should look like. Please note the 'Authorization: ' property.

GET https://localhost:44305/api/values/1 HTTP/1.1
Host: localhost:44305
User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64; rv:32.0) Gecko/20100101 Firefox/32.0
Accept: */*
Authorization: Bearer imSXTs2OqSrGWzsFQhIXziFCO3rF...
X-Requested-With: XMLHttpRequest
like image 175
txavier Avatar answered Nov 15 '22 05:11

txavier


Try this

string userId = HttpContext.Current.User.Identity.GetUserId();
like image 34
Antony Brahin Avatar answered Nov 15 '22 06:11

Antony Brahin