Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting Current User in .NET Core Console

Tags:

In a .NET Core console application (note: not ASP.NET Core!), how can I get the current user? To be clear, I'm looking for what used to be available as Thread.CurrentPrincipal, which no longer exists. PlatformServices does not contain this information, and neither does Environment.

like image 230
Ricardo Peres Avatar asked Apr 05 '16 14:04

Ricardo Peres


People also ask

How do I get the current UserName in .NET using C #?

GetCurrent(). Name; Returns: NetworkName\Username.


3 Answers

Got it. A possible option is to use WindowsIdentity:

WindowsIdentity.GetCurrent().Name 

It is necessary to add the System.Security.Principal.Windows package. Of course, this is for Windows only.

Another option is to use Claims:

ClaimsPrincipal.Current 

For that, the package to add is System.Security.Claims. In Windows, by default, the identity will be empty.

like image 94
Ricardo Peres Avatar answered Sep 18 '22 05:09

Ricardo Peres


System.Security.Principal.Windows is not available unless you import the DLL manually. The following worked for me:

Environment.UserName;

According to the .NET Core System.Environment Source Code, this solution "should suffice in 99% of cases."

Note: Be sure you are targeting DotNetCore 2.0 or later as 1.0 and 1.1 do not have this definition.

Edit Jan 22 2019: The link to the old source of the method has gone stale. PR 34654 moved System.Environment to live in CoreLib. For those curious to read the source code, you may still do so, though the comment suggesting it "should suffice in 99% of cases" has been removed.

like image 32
Foxtrek_64 Avatar answered Sep 21 '22 05:09

Foxtrek_64


If you want to reuse IIdentity abstraction to pass through your middle layer do this:

var identity = new GenericIdentity(Environment.UserDomainName + "\\" + Environment.UserName, "Anonymous");

P.S. in core 2 console app: ClaimsPrincipal.Current and Thread.CurrentPrincipal are always null (unless you have setup them) and this code will not work either:

IPrincipal principal = new GenericPrincipal(identity, null);
AppDomain.CurrentDomain.SetThreadPrincipal(principal);

after this ClaimsPrincipal.Current and Thread.CurrentPrincipal are still null.

WindowsIdentity.GetCurrent() works, but there should be more strong reasons to reference System.Security.Principal.Window then get the "user name".

like image 25
Roman Pokrovskij Avatar answered Sep 18 '22 05:09

Roman Pokrovskij