【问题标题】:How to get windows usernaame in ASP.NET Core 3.0如何在 ASP.NET Core 3.0 中获取 Windows 用户名
【发布时间】:2020-11-02 13:55:52
【问题描述】:

我正在尝试在 ASP.NET Core 3.0 中获取 windows 用户名

我在这里找到了很多关于这个主题的问题,但我找不到任何可以使用的答案。

我的应用程序使用登录密码身份验证,但很多用户(不是所有用户)都有自己的 Windows 登录名,所以我想给他们机会通过 Windows 登录名登录。

在本地主机上运行此代码:

string windowsUserName = Environment.UserDomainName + "\\" + Environment.UserName;

但是当我将它部署到服务器时,我得到了这个用户名: IIS APPPOOL/DefaultAppPool

我已尝试从以下位置更改启动设置:

"iisSettings": {
    "windowsAuthentication": false,
    "anonymousAuthentication": true,

到:

"iisSettings": {
    "windowsAuthentication": true,
    "anonymousAuthentication": true,

但我只能通过 HttpContext.User.Identity.Name 获取 Windows 登录名(我只在 localhost 上尝试过),但我不想使用这种方法 - 我在这里存储 Id来自数据库的用户,所以我不想重写它。

是否有机会在不为所有人使用 Windows 登录的情况下获取所需数据?

非常感谢您的建议。

【问题讨论】:

  • “我的应用程序使用登录密码验证”,然后您可以修改您的应用程序代码以允许他们填写 Windows 帐户名和密码进行登录,并且保持 IIS 设置不变。当您实际在 VS/IIS Express 上运行时,您对“localhost”的描述可能是错误的。有根本区别,blog.lextudio.com/…

标签: authentication windows-authentication asp.net-core-3.0 iis-10


【解决方案1】:

确保您的 web.config 如下:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <system.webServer>
    <handlers>
      <add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModule" resourceType="Unspecified" />
    </handlers>
    <aspNetCore forwardWindowsAuthToken="true" processPath="C:\Program Files\dotnet\dotnet.exe" arguments=".\YourWebsite.dll" stdoutLogEnabled="true" stdoutLogFile=".\logs\stdout" />
        <security>
            <authentication>
                <windowsAuthentication enabled="true" />
                <anonymousAuthentication enabled="false" />
            </authentication>
        </security>
  </system.webServer>
</configuration>

HomeController.cs 然后,您可以使用以下代码从控制器获取用户 Windows 用户名。

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

更新:

您在帖子中提到的称为混合模式身份验证。您无法通过使用单个应用程序来实现这一点,您需要使用两个应用程序来实现您的要求。请参阅this link 了解更多详细信息,如何实现这一点。

【讨论】:

  • 感谢您的建议,但正如我在问题中所写的那样 - 我正在使用 HttpContext.User.Identity.Name 作为我们公司内用户的 ID - 这是整个项目中的用户 - 所以要更改例如 Lex Li 所建议的那样是没有意义的。第二件事是,当我禁用anonymousAuthentication 时,用户名登录失败......
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-04-10
  • 1970-01-01
  • 1970-01-01
  • 2019-11-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多