How to get the current Windows user with ASP.NET Core RC2 MVC6 and IIS7
Asked Answered
S

4

23

I have an intranet site built in MVC6 using ASP.NET Core RC2. I want to get the Windows username of the person accessing the intranet site.

So if Jim goes to the intranet site I want the site to receive "Domain\Jim", while if Anne goes to the intranet site I want the site to receive "Domain\Anne".

Only Windows Authentication is enabled on my IIS server, Anonymous Authentication is disabled.

My site is set to use Windows authentication and to disable anonymous authentication.

<system.web>
    <authentication mode="Windows" />
    <authorization>
        <deny users="?"/>
    </authorization>
</system.web>

Through Debug I can use System.Security.Principal.WindowsIdentity.GetCurrent().Name, but that of course returns "IIS APPPOOL\SiteName" on the IIS server.

I found many examples from older version of ASP.NET using HttpContext, and I tried injecting that into my controller with the following but userName ends up null.

//Startup.cs
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();

//HomeController.cs
public HomeController(IHttpContextAccessor _accessor)
{
    string userName = _accessor.HttpContext.User.Identity.Name;
}

What is the correct way to pass the Windows username to an intranet site in ASP.NET Core RC2 MVC6?

Shrewish answered 6/7, 2016 at 21:21 Comment(13)
Have you disabled anonymous access to your site?Provolone
Yes. I disabled it with the following inside <system.web>. <authorization> <deny users="?"> </authorization> I've updated my question with the <system.web> block.Shrewish
Do you have any authentication middleware registered?Provolone
does your site have a login screen..? also do a google search there is information out there on how to do this. here is a freeB #30701506Barton
@Barton No login screen is needed with windows authProvolone
@Shrewish Perhaps this config will help https://mcmap.net/q/585941/-windows-authentication-in-asp-net-5Provolone
First, upgrade to RTM. Second, learn what is ASP.NET Core at docs.asp.net The settings you put in web.config are useless, as they are not for ASP.NET Core at all.Attica
I have Googled this extensively @MethodMan, but unfortunately most answers are for older versions of ASP.NET, not Core. The result is that most solutions, including the one you linked, do not work in ASP.NET Core. There is neither access to the System.Web.Current path nor is there a User.GetUserId() method.Shrewish
@Provolone I tried that config but it results in a 500 internal server error. Thank you though.Shrewish
Please, don't use MVC6 tags anymore. It's for a future version of ASP.NET MVC based on the old webstack (MVC5). ASP.NET Core is a complete new and incompatible, portable version based on .NET Core. Use asp.net-core-mvc and/or asp.net-core tags instead and your question is more likely to be found by people who can help you with the issueRapine
Has anyone has any luck with asp.net core and IIS to be able to read the subject? I have tried a lot of options I read but did not get it to work.Civvies
I can't get it to work when published to IIS either. I'm hoping someone can get this also.Greenwood
Did you solve this.. my issue... #58121076Riggall
F
19

Might help someone who are still looking for. Per documentation from MS https://learn.microsoft.com/en-us/aspnet/core/fundamentals/http-context?view=aspnetcore-2.2 , add the HttpContextAccessor in ConfigureServices method (startup.cs) Pass this httpcontextaccessor into the controller and access the logged in user.

I followed this and I was able to get the logged in Windows Authenticated user even after deploying the core website to IIS.

Here are the code snippets

In Startup.cs (under ConfigureServices method) add the line

services.AddHttpContextAccessor();

Then in your controller file, add following piece of necessary code lines. The code below is a sample.

public class YourController : Controller
{
  private readonly IHttpContextAccessor _httpContextAccessor;
  private readonly string _user;
  public YourController(IHttpContextAccessor httpContextAccessor)
  {
    _httpContextAccessor = httpContextAccessor;
    _user = _httpContextAccessor.HttpContext.User.Identity.Name;
  }
}
Fleshings answered 16/2, 2019 at 9:39 Comment(5)
I suggest this answer to be flagged as the correct answer to help many like me who spent a day looking for a solution. I had the same issue as in question, even after following all .net core related instructions. However, his answer, to inject HttpContextAccessor, works perfectly.Holtorf
My issue... #58121076Riggall
How come the user is NULL?Naked
in Properties/launchSettings, you may need to make your key/value pairs look like this: "windowsAuthentication": true, "anonymousAuthentication": false,Renie
How can I use this _user var in a custom (authrization) attribute? [Authorize("PRIVILE", _user)] => CS0182 An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter typeAfterbody
I
8

For anyone else using Windows Authentication on an Intranet app, who just wants to be able to retrieve info about a user, it's simpler that you might think.

In your controller, this line will grab the user name of the current user in DOMAIN\username form.

var userId = this.User.Identity.Name;

I spent some time looking through the other answers before realizing that most of them assumed I was implementing Individual accounts to be authenticated against AD, not out of the box Windows Authentication.

Italianate answered 3/2, 2017 at 18:2 Comment(4)
HI, if you run the Application from Visual Studio in Debug mode, "this.User.Identity.Name" should have a value, or it only Works under IIS? I am doing an Angular 5 App, on my Controllier I am having null....Ecumenism
Yes @Ecumenism I'm having the same issue. The above works when debugging application from Visual Studio but after publishing to IIS with Windows Auth enabled, the above comes back null. If anyone can text the above and confirm that it works after being published then I will change my vote and it will help myself very much. Thanks.Greenwood
I amusing that line in IIS to get the username I can't access the server right now to check setup, but if memory serves the biggest thing that helped me get this setup was setting the app pool to run on a domain account.Italianate
My issue.. #58121076Riggall
Q
0

Using var userId = this.User.Identity.Name; worked for me. My app is running on an intranet and all I was looking to do is get the user's login Id from Windows. I didn't need to store the user's information as that is already being stored in Active Directory.  

Quinidine answered 23/10, 2017 at 16:34 Comment(2)
Works for me until I publish to IIS.Greenwood
Same here.. I publish to IIS and it did not work.. #58121076Riggall
U
0

ServiceSecurityContext.Current?.PrimaryIdentity

Undies answered 16/11, 2018 at 5:14 Comment(1)
Looks like this requires ASP.NET Core 3+Virtuosic

© 2022 - 2024 — McMap. All rights reserved.