【发布时间】:2018-10-29 13:01:57
【问题描述】:
我正在尝试改进旧 ASPNet MVC/OWIN 应用程序的身份验证故事 - 目前,它使用 AspNetUsers / AspNetRoles / 声明等表以及基于表单 + cookie 的身份验证。
我想使用 Azure AD / OpenID Connect 进行身份验证,然后像当前一样从数据库中加载用户配置文件/角色。基本上,应用程序内不再有密码管理。用户本身仍然需要在应用中存在/被创建。
该应用程序非常依赖与这些用户关联的一些自定义数据,因此不能简单地使用 Active Directory 中的角色。
OpenID 身份验证有效,但我不确定如何结合使用现有的 Identityuser / IdentityUserRole / RoleManager 管道。
基本上,一旦用户使用 Open ID 进行身份验证,我们就会希望从数据库中加载相应的用户(匹配电子邮件地址)并使用该用户配置文件/角色。
特别是,AuthorizeAttribute(指定了特定角色)应该继续像以前一样工作。
这是我目前所拥有的:
public class IdentityConfig
{
public void Configuration(IAppBuilder app)
{
app.CreatePerOwinContext(AppIdentityDbContext.Create);
app.CreatePerOwinContext<AppUserManager>(AppUserManager.Create);
app.CreatePerOwinContext<AppRoleManager>(AppRoleManager.Create);
ConfigureAuth(app);
}
/// <summary>
/// Configures OpenIDConnect Authentication & Adds Custom Application Authorization Logic on User Login.
/// </summary>
/// <param name="app">The application represented by a <see cref="IAppBuilder"/> object.</param>
private void ConfigureAuth(IAppBuilder app)
{
app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
app.UseCookieAuthentication(new CookieAuthenticationOptions());
//Configure OpenIDConnect, register callbacks for OpenIDConnect Notifications
app.UseOpenIdConnectAuthentication(
new OpenIdConnectAuthenticationOptions
{
ClientId = ConfigHelper.ClientId,
Authority = String.Format(CultureInfo.InvariantCulture, ConfigHelper.AadInstance,
ConfigHelper.Tenant), // For Single-Tenant
PostLogoutRedirectUri = ConfigHelper.PostLogoutRedirectUri,
TokenValidationParameters = new System.IdentityModel.Tokens.TokenValidationParameters
{
RoleClaimType = "roles",
},
Notifications = new OpenIdConnectAuthenticationNotifications
{
AuthenticationFailed = context =>
{
context.HandleResponse();
context.Response.Redirect("/Error/OtherError?errorDescription=" +
context.Exception.Message);
return Task.FromResult(0);
},
SecurityTokenValidated = async context =>
{
string userIdentityName = context.AuthenticationTicket.Identity.Name;
var userManager = context.OwinContext.GetUserManager<AppUserManager>();
var user = userManager.FindByEmail(userIdentityName);
if (user == null)
{
Log.Error("User {name} authenticated with open ID, but unable to find matching user in store", userIdentityName);
context.HandleResponse();
context.Response.Redirect("/Error/NoAccess?identity=" + userIdentityName);
return;
}
user.DateLastLogin = DateTime.Now;
IdentityResult result = await userManager.UpdateAsync(user);
if (result.Succeeded)
{
var authManager = context.OwinContext.Authentication;
ClaimsIdentity ident = await userManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ExternalBearer);
// Attach additional claims from DB user
authManager.User.AddIdentity(ident);
// authManager.SignOut();
// authManager.SignIn(new AuthenticationProperties { IsPersistent = false }, ident);
return;
}
throw new Exception(string.Format("Failed to update user {0} after log-in", userIdentityName));
}
}
});
}
}
【问题讨论】:
-
我陷入了类似的境地。您第一次是如何将 Azure Ad 用户注册到数据库服务器的?您是否使用虚拟密码注册或使用 CreateIdentityAsync 与外部承载?
-
我打电话给
UserManager.CreateAsync(user),传入新用户的详细信息(名字、姓氏、电子邮件等 - 无密码)。在我的AppUserManager的构造函数中,我分配了一个自定义UserValidator实例,带有选项AllowOnlyAlphanumericUserNames = false和RequireUniqueEmail = true。 HTH
标签: entity-framework asp.net-identity azure-active-directory owin openid-connect