azure HttpContext.当前.用户.标识.非Windows用户的替代名称?

mqxuamgl  于 2023-01-31  发布在  Windows
关注(0)|答案(2)|浏览(162)

我将应用程序部署到Azure。具有Windows帐户的内部用户在导航到应用程序时自动登录。外部用户需要输入其用户名和密码才能登录到应用程序。他们的用户名是一个电子邮件地址,其域与内部用户使用的域不同。
我使用HttpContext.Current.User.Identity.Name来设置CreatedByModifiedBy的值。我还在视图中使用@User.Identity.Name来显示问候语。这两个值都不为具有非Windows帐户的外部用户显示值。
非Windows帐户有哪些替代选项可以获取这些值?
Startup.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之后,我还检查了Active Directory用户配置文件是否有任何缺失值,例如电子邮件地址或名称。

jbose2ul

jbose2ul1#

在ASP.NET核心中,可以通过HttpContext类上的User属性访问当前用户的标识信息。
然而,HttpContext.Current属性在ASP.NET核心中不可用。相反,您可以使用依赖项注入来获取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类的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();
  }

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

[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登录名。
  • 如果应用程序使用窗体身份验证,则User.Identity.Name属性将返回用户登录时输入的用户名。

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

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

Windows登录:

参考:Forms and Windows Authentication感谢@ mvolo的博客。

mspsb9vt

mspsb9vt2#

对于此问题,我将NameClaimType = ClaimTypes.Upn更新为NameClaimType = ClaimTypes.Name
我第一次选择Upn而不是Name是因为根据他们的描述,Upn似乎更“独特”。
我与外部用户确认了用户名现在已显示。

相关问题