简体   繁体   English

Asp net Core 获取用户 Windows 用户名

[英]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.在 ASP .net CORE mvc 中构建 Intranet,我需要获取当前用户的 Windows 用户名进行登录,我不需要使用 Windows 身份验证自动登录用户,我已经有一个自定义登录控制器来做到这一点,我只需要他的用户名。
It work fine on local but I cannot get the username when on the IIS server :它在本地运行良好,但在 IIS 服务器上无法获取用户名:
Local :当地的 :

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

IIS server : IIS服务器:

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

With Windows Auhtentication it auto login me which is not what I need.使用 Windows 身份验证它会自动登录我,这不是我需要的。 There must be 2 type of authentication : Automatic with AD and Manual with form manage by Identity Framework.必须有 2 种类型的身份验证:自动使用 AD 和手动使用身份框架管理表单。

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 : ASP .net 似乎没有授权 2 种不同类型的连接,所以我让主站点使用表单身份验证,并创建了一个小 API:

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

Configure with Windows Authentication.使用 Windows 身份验证进行配置。
And here's the LoginController in the main website :这是主网站中的 LoginController :

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在 ASP .NET Core 中获取 Windows 用户名

First update the windowsAuthentication and anonymousAuthentication properties in your launchSettings.json file.首先更新launchSettings.json 文件中的windowsAuthentication 和anonymousAuthentication 属性。 Anonymous site access is still possible.匿名站点访问仍然是可能的。

launchSettings.json启动设置.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.然后,您可以使用以下代码从控制器获取用户 Windows 用户名。

HomeController.cs家庭控制器.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.如果您想在启动脚本或存储库中访问 Windows 用户名,那么您可以依赖注入 HttpContextAccessor,这将允许访问用户对象。 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/ https://blog.bitscry.com/2020/05/05/getting-the-windows-user-name-in-asp-net-core/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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