【问题标题】:Asp net Core Get user Windows usernameasp net Core 获取用户Windows用户名
【发布时间】:2018-07-16 07:24:32
【问题描述】:

在 ASP .net CORE mvc 中构建内网,我需要获取当前用户的 Windows 用户名进行登录,我不需要使用 Windows Authentication 自动登录用户,我已经有一个自定义登录控制器要做那,我只需要他的用户名。
它在本地工作正常,但在 IIS 服务器上我无法获取用户名:
本地:

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

IIS 服务器:

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

使用 Windows 身份验证,它会自动登录我,这不是我需要的。 必须有 2 种类型的身份验证:自动使用 AD 和手动使用身份框架管理的表单。

【问题讨论】:

    标签: c# asp.net authentication asp.net-core active-directory


    【解决方案1】:

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

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

    使用 Windows 身份验证进行配置。
    这是主网站中的 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
            }
    }
    

    【讨论】:

      【解决方案2】:

      在 ASP .NET Core 中获取 Windows 用户名

      首先更新您的launchSettings.json 文件中的windowsAuthentication 和anonymousAuthentication 属性。匿名网站访问仍然是可能的。

      launchSettings.json

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

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

      HomeController.cs

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

      依赖注入

      如果您想在启动脚本或存储库中访问 Windows 用户名,那么您可以依赖注入 HttpContextAccessor,这将允许访问 User 对象。更多细节可以在这里找到。

      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/

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-09-03
        • 1970-01-01
        • 2021-12-14
        • 2017-07-26
        • 1970-01-01
        • 1970-01-01
        • 2023-04-10
        相关资源
        最近更新 更多