I'm trying to get current logged-in windows userId using .Net-Core 2.0. What is the correct way to achieve this in .Net-core 2.0? Also what are the Groups which this user is member of?
-
Have you seen this? https://stackoverflow.com/questions/36641338/how-get-current-user-in-asp-net-core – Captain Whippet Dec 19 '17 at 23:09
-
Yes, I've tried with this. But no luck. var userId = httpContextAccessor.HttpContext.User.FindFirst(ClaimTypes.NameIdentifier); returns null. What am I missing here. – MBK Dec 21 '17 at 13:39
-
Some sample code might help others answer the question. See https://stackoverflow.com/help/how-to-ask – Captain Whippet Dec 21 '17 at 16:08
2 Answers
This question is a bit old now, but I haven't found an answer on SO to this specific setup where:
ClaimsPrincipal currentUser = this.User;
var currentUserName = currentUser.FindFirst(ClaimTypes.NameIdentifier).Value;
currentUserName
returns null
Setup
I have two servers:
- Identity Server
- Client Server
The Authentication server and the Client server on separate projects (or domains). So there isn't any communication between them (except for authorization)
The Identity server uses Jwt Tokens for authentication.
In Startup.cs
of the Identity server:
public void ConfigureServices(IServiceCollection services)
{
...
var identityBuilder = services.AddIdentityServer();
identityBuilder
.AddInMemoryApiResources(
new List<ApiResource>
{
new ApiResource("app name", "app displayname", new[] { JwtClaimTypes.Role, JwtClaimTypes.Name}) {UserClaims = {JwtClaimTypes.Name, JwtClaimTypes.Role}}
};
)
...
}
^^ this is important for the Solution section
The problem
When a user does a call to the Client Server, the server can't really access the client's credentials without making an additional call to the Identity Server (and this might be technically incur a some form of a security risk)
Solution: Poor man's Jwt Claim Types username extractor
So I wrote a small extension function to extract some form of username from the ClaimsPrincipal
, this isn't fool proof, but it should at least be of some use.
public static string GetUsername(this ClaimsPrincipal user)
{
var username = user?.Identity?.Name;
if (username != null)
{
return username;
}
// Get username from claim, this is usualy an email
var claim = user?.FindFirst(x => x.Type == JwtClaimTypes.PreferredUserName) ??
user?.FindFirst(x => x.Type == JwtClaimTypes.Name);
if (claim == null)
{
return null;
}
username = claim.Value;
var atIndex = username.IndexOf('@');
if (atIndex > 0)
{
username = username.Substring(0, atIndex);
var name = username.Split('.', StringSplitOptions.RemoveEmptyEntries);
username = "";
foreach (var n in name)
{
if (n.Length > 2)
{
username += n.First().ToString().ToUpper() + n.Substring(1) + " ";
}
else
{
username += n.ToUpper() + " ";
}
}
}
return username.Trim();
}
What this code basically does is: it takes the ClaimsPrincipal
and tries to extract the Name of the user, since the username is almost always an email it tries to parse the email to return the User Name. It's only usable if the username is something parsable.
Hope this helps.

- 1
- 1

- 2,904
- 1
- 19
- 34
In your controller, do: User.Identity.GetUserId();
.
Otherwise, you need to inject IHttpContextAccessor _http;
in your class and then _http.HttpContext.User?.Identity?.GetUserId();
. Sample beneath:
public class Test
{
private readonly IHttpContextAccessor _http;
public Test(IHttpContextAccessor http)
{
_http = http;
}
public int? GetUserId()
{
return _http.HttpContext.User?.Identity?.GetUserId();
}
}

- 457
- 1
- 3
- 22
-
Hammarstrom: I'm using .Net-Core 2.0. User.Identity class in System.Security.Principal does not have GetUserId() implementation. namespace System.Security.Principal { public interface IIdentity { string AuthenticationType { get; } bool IsAuthenticated { get; } string Name { get; } } } Also User.Identity.Name return null. How to get it done this? – MBK Dec 22 '17 at 08:44
-
Have you solve this problem? I algo need to get current logged-in windows userid. thanks – Diego Mar 28 '18 at 13:08
-
see here https://stackoverflow.com/questions/46273107/how-to-get-user-id-of-logged-in-user-in-net-core-2-0 – Diego Mar 28 '18 at 14:20