Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get user id of logged in user in .NET Core 2.0?

I have created a angular 2 application using .NET Core and MVC. I want to know the login id of user. How to get logged in id of a user in .net core?

This is my first angular application. I used following link to start https://blogs.msdn.microsoft.com/webdev/2017/02/14/building-single-page-applications-on-asp-net-core-with-javascriptservices/

I want to use windows authentication, to get login id in a controller.

like image 421
Mandar Patil Avatar asked Sep 18 '17 06:09

Mandar Patil


People also ask

How do I find my UserName for net core?

NameIdentifier gives the current user id, and ClaimTypes.Name gives the username.

How can I get UserName in asp net?

Use the UserDomainName property to obtain the user's domain name and the UserName property to obtain the user name. On Unix platforms the UserName property wraps a call to the getpwuid_r function. If an ASP.NET application runs in a development environment, the UserName property returns the name of the current user.

What is HttpContext user identity Name?

It just holds the username of the user that is currently logged in. After login successful authentication, the username is automatically stored by login authentication system to "HttpContext.Current.User.Identity.Name" property.

What is IHttpContextAccessor?

HTTP context accessor. Finally, you can use the IHttpContextAccessor helper service to get the HTTP context in any class that is managed by the ASP.NET Core dependency injection system. This is useful when you have a common service that is used by your controllers.


1 Answers

That really depends on what kind of authentication you have in your app.

Considering you mentioned Angular, I'm not sure what framework you use for authentication, and what are your settings.

To get you moving into the right direction, your course of action would be getting the relevant claim from the user identity. Something like this:

var ident = User.Identity as ClaimsIdentity;
var userID = ident.Claims.FirstOrDefault(c => c.Type == idClaimType)?.Value;

where idClaimType is the type of the claim that stores your Identity. Depending on the framework, it would usually either be
ClaimTypes.NameIdentifier (= "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier")
or
JwtClaimTypes.Subject (= "sub")

If you're using Asp.Net Core Identity, you could use their helper method on the UserManager to simplify access to it:

UserManager<ApplicationUser> _userManager;
[…]
var userID = _userManager.GetUserId(User);
like image 100
Artiom Chilaru Avatar answered Oct 25 '22 13:10

Artiom Chilaru