5

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
{
    ....
SharpC
  • 6,974
  • 4
  • 45
  • 40
Alexe Barlescu
  • 387
  • 4
  • 11
  • What authentication are you using for your web api? – Nkosi Jul 19 '16 at 14:40
  • The reason the MVC works is because you are probably using authentication (like a cookie) – Nkosi Jul 19 '16 at 14:40
  • Sorry i don't get that, both controller the mvc and api are part of same application, on Controllers folder. Using individual user accounts authentication. – Alexe Barlescu Jul 19 '16 at 14:46
  • Same project/application, different frameworks under common name. You have to setup the authentication for web api separately http://www.asp.net/web-api/overview/security – Nkosi Jul 19 '16 at 15:45
  • check this topic https://stackoverflow.com/questions/28657852/how-to-get-user-context-during-web-api-calls – Khachatur Nov 01 '17 at 05:45

4 Answers4

1

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
txavier
  • 481
  • 4
  • 6
1

Try this

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

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());
        }
Kawindu
  • 31
  • 1
0
string id = RequestContext.Principal.Identity.GetUserId();

Try using this when you have an ApiController.

Kerim Emurla
  • 1,141
  • 8
  • 15