Get the current user, within an ApiController action, without passing the userID as a parameter

C#asp.netasp.net Web-Apiasp.net Identity

C# Problem Overview


How do we get the current user, within an secure ApiController action, without passing the userName or userId as a parameter?

We assume that this is available, because we are within a secure action. Being in a secure action means that the user has already authenticated and the request has her bearer token. Given that WebApi has authorized the user, there may be a built in way to access the userId, without having to pass it as an action parameter.

C# Solutions


Solution 1 - C#

In WebApi 2 you can use RequestContext.Principal from within a method on ApiController

Solution 2 - C#

You can also access the principal using the User property on ApiController.

So the following two statements are basically the same:

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

Solution 3 - C#

Hint lies in Webapi2 auto generated account controller

Have this property with getter defined as

public string UserIdentity
        {
            get
            {
                var user = UserManager.FindByName(User.Identity.Name);
                return user;//user.Email
            }
        }

and in order to get UserManager - In WebApi2 -do as Romans (read as AccountController) do

public ApplicationUserManager UserManager
        {
            get { return HttpContext.Current.GetOwinContext().GetUserManager<ApplicationUserManager>(); }
        }

This should be compatible in IIS and self host mode

Solution 4 - C#

None of the suggestions above worked for me. The following did!

HttpContext.Current.Request.LogonUserIdentity.Name

I guess there's a wide variety of scenarios and this one worked for me. My scenario involved an AngularJS frontend and a Web API 2 backend application, both running under IIS. I had to set both applications to run exclusively under Windows Authentication.

No need to pass any user information. The browser and IIS exchange the logged on user credentials and the Web API has access to the user credentials on demand (from IIS I presume).

Solution 5 - C#

Karan Bhandari's answer is good, but the AccountController added in a project is very likely a Mvc.Controller. To convert his answer for use in an ApiController change HttpContext.Current.GetOwinContext() to Request.GetOwinContext() and make sure you have added the following 2 using statements:

using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.Owin;

Solution 6 - C#

In .Net Core use User.Identity.Name to get the Name claim of the user.

Solution 7 - C#

If you are using Asp.Identity UseManager, it automatically sets the value of

> RequestContext.Principal.Identity.GetUserId()

based on IdentityUser you use in creating the IdentityDbContext.

If ever you are implementing a custom user table and owin token bearer authentication, kindly check on my answer.

https://stackoverflow.com/questions/28657852/how-to-get-user-context-during-web-api-calls/39262408#39262408

Hope it still helps. :)

Solution 8 - C#

string userName;
string userId;
if (HttpContext.Current != null && HttpContext.Current.User != null 
        && HttpContext.Current.User.Identity.Name != null)
{
    userName = HttpContext.Current.User.Identity.Name;
    userId = HttpContext.Current.User.Identity.GetUserId();
}

Or based on Darrel Miller's comment, maybe use this to retrieve the HttpContext first.

// get httpContext
object httpContext;
actionContext.Request.Properties.TryGetValue("MS_HttpContext", out httpContext);    

See also:

How to access HTTPContext from within your Web API action

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionShaun LuttinView Question on Stackoverflow
Solution 1 - C#Darrel MillerView Answer on Stackoverflow
Solution 2 - C#PatrickView Answer on Stackoverflow
Solution 3 - C#Karan BhandariView Answer on Stackoverflow
Solution 4 - C#kannankerilView Answer on Stackoverflow
Solution 5 - C#Jeff LeachView Answer on Stackoverflow
Solution 6 - C#Venkatesh MuniyandiView Answer on Stackoverflow
Solution 7 - C#pampiView Answer on Stackoverflow
Solution 8 - C#Shaun LuttinView Answer on Stackoverflow