简体   繁体   中英

Asp net Core Get user Windows username

Building an intranet in ASP .net CORE mvc, I need to get the Windows username of the current user for the login, I do not need to automaticaly login the user with Windows Authentication, I have already a custom login Controller to do that, I only need his username.
It work fine on local but I cannot get the username when on the IIS server :
Local :

Environment.UserName => VeronY 
System.Security.Principal.WindowsIdentity.GetCurrent().Name => Domain\VeronY

IIS server :

Environment.UserName => Intranet
System.Security.Principal.WindowsIdentity.GetCurrent().Name => APPPOOL\Intranet 

With Windows Auhtentication it auto login me which is not what I need. There must be 2 type of authentication : Automatic with AD and Manual with form manage by Identity Framework.

ASP .net doesn't seem to authorize 2 different types of connection, so I let the main site with form authentication and I 've created a small API :

[Authorize]
[Route("api/[controller]")]
public class ValuesController : Controller
{
    [HttpGet]
    public ActionResult Get()
    {
        return Json(User.Identity.Name);
    }
}

Configure with Windows Authentication.
And here's the LoginController in the main website :

String responseString = "";
        using (var client = new HttpClient())
        {
            client.BaseAddress = new Uri("http://myapiURL");
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            var response = client.GetAsync("api/values").Result;
            if (response.IsSuccessStatusCode)
            {
                responseString = response.Content.ReadAsStringAsync().Result;
                responseString = Regex.Unescape(responseString).Replace("\"","");//Because the response is something like \\"Domaine\\\\Username\"\
            }
            else
            {
                return View();//server cannot be found or Windows authentication fail => form Login
            }
        }
        String username = "";
        String domain = "";

        if (responseString != "" && responseString.Contains("\\"))
        {
            domain = responseString.Split('\\')[0];
            username = responseString.Split("\\")[1];
            if(domain !="MYDOMAIN")
            {
                return View();//Not in the correct domain => form Login
            }
        }
        else
        {
            return View();//Not the correct response => form Login
        }
        UserPrincipal user = UserPrincipal.FindByIdentity(new PrincipalContext(ContextType.Domain), username);


        if (null != user)
        {
            CustomAutomaticLogin(user)//All seems ok, try to log the user with custom login with AD informations
        }
        else
        {
           return View()//Not in AD => form login
        }
}

Getting the Windows User Name in ASP .NET Core

First update the windowsAuthentication and anonymousAuthentication properties in your launchSettings.json file. Anonymous site access is still possible.

launchSettings.json

"iisSettings": {
    "windowsAuthentication": true,
    "anonymousAuthentication": false,
    "iisExpress": {
        "applicationUrl": "http://localhost:53321",
        "sslPort": 44320
    }
}

You can then get a users Windows username from a controller using the below code.

HomeController.cs

public IActionResult Index()
{
    string userName = HttpContext.User.Identity.Name;
    return View(userName);
}

Dependency Injection

If you want to access the Windows username in the Startup script or in repositories then you can dependency inject the HttpContextAccessor which will allow access to the User object. Further details can be found here.

public virtual void ConfigureServices(IServiceCollection services)
{
    services.AddHttpContextAccessor();
    services.AddControllers();
}

https://blog.bitscry.com/2020/05/05/getting-the-windows-user-name-in-asp-net-core/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM