Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET Core detecting Mac OS user

I have created a .Net Core RC2 Web Application using VS2015 with windows authentication.

I then copied the project over to Mac OSX El Capitan and launched the app using the Terminal.

The application started as expected, however, as the application is running on my Mac there is no Windows user to display.

How can you return the Mac user and display the name?

This would also be useful for Linux users.

like image 953
shammelburg Avatar asked Mar 10 '26 14:03

shammelburg


1 Answers

To get the username of a user visited the website

You may be thinking of the "Windows Authentication" feature of IIS. IIS does some magic to authenticate the user visiting the website against a Windows domain and then forwards that Windows auth token to ASP.NET Core. ASP.NET Core can only use this feature when hosted using IIS (or IIS Express) and using the IIS Integration middleware. See https://github.com/aspnet/IISIntegration. Because IIS is Windows only, this means it is not possible to get a client username when hosting the website on Linux or OSX.

To get the username of the account hosting the web server

As of .NET Core 1.0, there is no cross-platform API for getting a username directly. If you are on windows, System.Security.Principal.WindowsIdentity works, but this will throw PlatformNotSupported on Linux/macOS.

By convention, many systems set the username in an environment variable. You can use System.Environment to fetch this.

var username = Environment.GetEnvironmentVariable("USERNAME") ??
               Environment.GetEnvironmentVariable("USER");

Another but more complicated approach is to p/invoke to native system calls that return information about the user, such as getpwuid_r (See the man pages for Linux and OSX.)

like image 57
natemcmaster Avatar answered Mar 13 '26 04:03

natemcmaster



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!