我将应用程序部署到Azure。具有Windows帐户的内部用户在导航到应用程序时自动登录。外部用户需要输入其用户名和密码才能登录到应用程序。他们的用户名是一个电子邮件地址,其域与内部用户使用的域不同。
我使用HttpContext.Current.User.Identity.Name
来设置CreatedBy
和ModifiedBy
的值。我还在视图中使用@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用户配置文件是否有任何缺失值,例如电子邮件地址或名称。
2条答案
按热度按时间jbose2ul1#
在ASP.NET核心中,可以通过HttpContext类上的User属性访问当前用户的标识信息。
然而,HttpContext.Current属性在ASP.NET核心中不可用。相反,您可以使用依赖项注入来获取IHttpContextAccessor接口的示例,并使用它来访问当前HttpContext。
1.在Startup.cs文件中,在ConfigureServices方法中配置身份验证:
在startup.cs类的configure方法中,对内部和外部用户使用UseWindowsAuthentication和UseCookieAuthentication。
创建处理外部用户登录的Login操作方法:
我使用HttpContext.Current.User.Identity.Name来设置CreatedBy和ModifiedBy值。我还在视图中使用@User.Identity.Name来显示问候语。对于具有非Windows帐户的外部用户,这两个选项都不显示值。
在视图中,可以使用以下代码检查用户是否经过身份验证。
Windows登录:
参考:Forms and Windows Authentication感谢@ mvolo的博客。
mspsb9vt2#
对于此问题,我将
NameClaimType = ClaimTypes.Upn
更新为NameClaimType = ClaimTypes.Name
。我第一次选择
Upn
而不是Name
是因为根据他们的描述,Upn
似乎更“独特”。我与外部用户确认了用户名现在已显示。