Alexe Barlescu
Alexe Barlescu

Reputation: 397

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
{
    ....

Upvotes: 5

Views: 5278

Answers (4)

Kawindu
Kawindu

Reputation: 31

Below Code will help to solve this issue.

using (josd_databaseEntities entities = new josd_databaseEntities())
            {
                josddevotee user = entities.josddevotees.Where
                <josddevotee>(r => r.Devt_Email == context.UserName && r.Devt_Password == context.Password).FirstOrDefault();

                if (user == null)
                {
                    context.SetError("invalid_grant", "The user name or password is incorrect.");
                    return;
                }
                else
                {
                    string id = user.Devt_ID.ToString();
                    identity.AddClaim(new Claim(ClaimTypes.Role, "user"));
                    identity.AddClaim(new Claim("username", context.UserName));
                    **identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, id));**
                    context.Validated(identity);
                }
            }

In the Controller.

public IHttpActionResult Get()
        {
            var identity = (ClaimsIdentity)User.Identity;
            return Ok(User.Identity.GetUserId());
        }

Upvotes: 1

Antony Brahin
Antony Brahin

Reputation: 29

Try this

string userId = HttpContext.Current.User.Identity.GetUserId();

Upvotes: 1

txavier
txavier

Reputation: 479

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

Upvotes: 1

Kerim Emurla
Kerim Emurla

Reputation: 1151

string id = RequestContext.Principal.Identity.GetUserId();

Try using this when you have an ApiController.

Upvotes: 0

Related Questions