[英]HttpContext.Current.User.Identity.Name Alternative for Non-Windows User?
我向 Azure 部署了一个应用程序。具有 Windows 帐户的内部用户在导航到该应用程序时会自动登录。 外部用户需要输入用户名和密码才能登录应用程序。 他们的用户名是一个 email 地址,其域名与内部用户使用的域名不同。
我使用HttpContext.Current.User.Identity.Name
来设置CreatedBy
和ModifiedBy
值。 我还在视图中使用@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);
}
}
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 帐户的外部用户的值。
在视图中,您可以使用以下代码来检查用户是否已通过身份验证。
@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.