繁体   English   中英

HttpContext.Current.User.Identity.Name 非 Windows 用户的替代方案?

[英]HttpContext.Current.User.Identity.Name Alternative for Non-Windows User?

我向 Azure 部署了一个应用程序。具有 Windows 帐户的内部用户在导航到该应用程序时会自动登录。 外部用户需要输入用户名和密码才能登录应用程序。 他们的用户名是一个 email 地址,其域名与内部用户使用的域名不同。

我使用HttpContext.Current.User.Identity.Name来设置CreatedByModifiedBy值。 我还在视图中使用@User.Identity.Name来显示问候语。 这两个都不显示具有非 Windows 帐户的外部用户的值。

非 Windows 帐户获取这些值的替代选项是什么?

启动.Auth.cs

public partial class Startup
{
    public void ConfigureAuth(IAppBuilder app)
    {
        var clientId = ConfigurationManager.AppSettings["ida:ClientId"];
        var aADInstance = ConfigurationManager.AppSettings["ida:AADInstance"];
        var tenantId = ConfigurationManager.AppSettings["ida:TenantId"];
        var postLogoutRedirectUri = ConfigurationManager.AppSettings["ida:PostLogoutRedirectUri"];
        var authority = string.Format(CultureInfo.InvariantCulture, aADInstance, tenantId);

        app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

        app.UseCookieAuthentication(new CookieAuthenticationOptions
        {
            AuthenticationType = "Cookies",
            CookieManager = new SystemWebChunkingCookieManager()
        });

        app.UseOpenIdConnectAuthentication(
            new OpenIdConnectAuthenticationOptions
            {
                ClientId = clientId,
                Authority = authority,
                PostLogoutRedirectUri = postLogoutRedirectUri,
                TokenValidationParameters = new TokenValidationParameters
                {
                    NameClaimType = ClaimTypes.Upn,
                    RoleClaimType = ClaimTypes.Role
                },
                Notifications = new OpenIdConnectAuthenticationNotifications
                {
                    AuthenticationFailed = context =>
                    {
                        context.HandleResponse();
                        context.Response.Redirect("/");
                        return Task.FromResult(0);
                    }
                }
            }
        );
    }
}

我尝试查看HttpContext.Current.User.Identity.Name是否有其他选项来获取所需的值,例如在Identity之后和User之后。 我还检查了活动目录用户配置文件是否有任何缺失值,例如 email 地址或名称。

在ASP.NET Core中,可以通过HttpContext class上的User属性获取当前用户的身份信息。

而 HttpContext.Current 属性在 ASP.NET Core 中不可用。 相反,您可以使用依赖项注入来获取 IHttpContextAccessor 接口的实例,并使用它来访问当前的 HttpContext。

public class HomeController : Controller
    {
        private readonly IHttpContextAccessor _contextAccessor;

        public HomeController(IHttpContextAccessor contextAccessor)
        {
            _contextAccessor = contextAccessor;
        }

        public IActionResult Index()
        {
            var userName = _contextAccessor.HttpContext.User.Identity.Name;

            if (string.IsNullOrEmpty(userName) && _contextAccessor.HttpContext.User.Identity.IsAuthenticated)
            {
                userName = _contextAccessor.HttpContext.User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Email)?.Value;
            }

            return View(userName);
        }
    }

  1. 在 Startup.cs 文件中,在 ConfigureServices 方法中配置身份验证:
public void ConfigureServices(IServiceCollection services)
{
    services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
        .AddCookie(options =>
        {
            options.LoginPath = new PathString("/Account/Login");
            options.AccessDeniedPath = new PathString("/Account/AccessDenied");
        });
    
}

在 startup.cs class 中,在 configure 方法中,为内部和外部用户使用 UseWindowsAuthentication 和 UseCookieAuthentication。

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    app.Use(async (context, next) =>
    {
        if (context.User.Identity.IsAuthenticated && context.User.Identity.AuthenticationType == "NTLM")
        {
            var email = context.User.Identity.Name;
            if (!email.EndsWith("@internal-domain.com"))
            {
                await context.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
                context.Response.Redirect("/Account/Login");
                return;
            }
        }

        await next();
    });
    app.UseWindowsAuthentication();
    app.UseCookieAuthentication();
  }

创建处理外部用户登录的登录操作方法:

[HttpPost]
public async Task<IActionResult> Login(LoginViewModel model)
{
    if (ModelState.IsValid)
    {
        
        if (IsValidUser(model.Email, model.Password))
        {
            
            if (!model.Email.EndsWith("@internal-domain.com"))
            {
                var identity = new ClaimsIdentity(CookieAuthenticationDefaults.AuthenticationScheme);
                identity.AddClaim(new Claim(ClaimTypes.Name, model.Email));
                await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(identity));
                return RedirectToAction("Index", "Home");
            }
            else
            {
                ModelState.AddModelError("", "Invalid UserName.");
            }
        }
        else
        {
            ModelState.AddModelError("", "Invalid password.");
        }
    }
    return View(model);
}

private bool IsValidUser(string email, string password)
{
    // check with DB to compare the credentials.
    return true;
}

我使用 HttpContext.Current.User.Identity.Name 来设置 CreatedBy 和 ModifiedBy 值。 我还在视图中使用@User.Identity.Name 来显示问候语。 这两个都不显示具有非 Windows 帐户的外部用户的值。

  • HttpContext.Current.User.Identity.Name 和@User.Identity.Name 用于在 ASP.NET 应用程序中检索用户名。
  • 这些属性基于应用程序中使用的身份验证机制。
  • 如果应用程序使用 Windows 身份验证,则 User.Identity.Name 属性将返回用户的 Windows 登录名。
  • 如果应用程序使用 forms 身份验证,则 User.Identity.Name 属性将返回用户在登录时输入的用户名。

在视图中,您可以使用以下代码来检查用户是否已通过身份验证。

@if (User.Identity.IsAuthenticated)
{
    <text>Welcome, @User.Identity.Name</text>
}
else
{
    <text>Welcome, User</text>
}

Windows 登录:

在此处输入图像描述

在此处输入图像描述

参考: Forms 和 Windows 身份验证感谢@mvolo 的博客。

对于这个问题,我将NameClaimType = ClaimTypes.Upn更新为NameClaimType = ClaimTypes.Name

我首先选择了Upn而不是Name ,因为根据他们的描述, Upn似乎更“独特”。

我与外部用户确认现在显示了用户名。

暂无
暂无

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

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