【问题标题】:How to authenticate with Azure AD / OpenId but use Entity Framework based user/role data如何使用 Azure AD / OpenId 进行身份验证,但使用基于实体框架的用户/角色数据
【发布时间】: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


【解决方案1】:

这是我最终做的:

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
        {
            CookieDomain = ConfigHelper.AuthCookieDomain,
            SlidingExpiration = true,
            ExpireTimeSpan = TimeSpan.FromHours(2)
        });

        //Configure OpenIDConnect, register callbacks for OpenIDConnect Notifications
        app.UseOpenIdConnectAuthentication(
            new OpenIdConnectAuthenticationOptions
            {
                ClientId = ConfigHelper.ClientId,
                Authority = String.Format(CultureInfo.InvariantCulture, ConfigHelper.AadInstance, ConfigHelper.Tenant),

                TokenValidationParameters = new System.IdentityModel.Tokens.TokenValidationParameters
                {
                    RoleClaimType = ClaimTypes.Role
                },

                Notifications = new OpenIdConnectAuthenticationNotifications
                {
                    AuthenticationFailed = context =>
                    {
                        context.HandleResponse();
                        context.Response.Redirect("/Error/OtherError?errorDescription=" + context.Exception.Message);
                        return Task.FromResult(0);
                    },
                    RedirectToIdentityProvider = context =>
                    {
                        // Set the post-logout & redirect URI dynamically depending on the incoming request.
                        // That allows us to use the same Azure AD app for two subdomains (these two domains give different app behaviour)
                        var builder = new UriBuilder(context.Request.Uri);
                        builder.Fragment = builder.Path = builder.Query = "";
                        context.ProtocolMessage.PostLogoutRedirectUri = builder.ToString();
                        context.ProtocolMessage.RedirectUri = builder.ToString();
                        return Task.FromResult(0);
                    }
                }
            });

        app.Use<EnrichIdentityWithAppUserClaims>();
    }
}

public class EnrichIdentityWithAppUserClaims : OwinMiddleware
{
    public EnrichIdentityWithAppUserClaims(OwinMiddleware next) : base(next)
    {
    }

    public override async Task Invoke(IOwinContext context)
    {
        await MaybeEnrichIdentity(context);
        await Next.Invoke(context);
    }

    private async Task MaybeEnrichIdentity(IOwinContext context)
    {
        ClaimsIdentity openIdUserIdentity = (ClaimsIdentity)context.Authentication.User.Identity;
        string userIdentityName = openIdUserIdentity.Name;

        var userManager = context.GetUserManager<AppUserManager>();
        var appUser = userManager.FindByEmail(userIdentityName);

        if (appUser == null)
        {
            Log.Error("User {name} authenticated with open ID, but unable to find matching user in store", userIdentityName);
            return;
        }

        appUser.DateLastLogin = DateTime.Now;
        IdentityResult result = await userManager.UpdateAsync(appUser);
        if (result.Succeeded)
        {
            ClaimsIdentity appUserIdentity = await userManager.CreateIdentityAsync(appUser, DefaultAuthenticationTypes.ExternalBearer);
            openIdUserIdentity.AddClaims(appUserIdentity.Claims);
        }
    }
}

它与我最初的非常相似 - (注意:RoleClaimType = ClaimTypesRoles 不是“角色”)除了尝试在 SecurityTokenValidated 回调中处理用户之外,我添加了一些自定义中间件来找到匹配项用户(通过电子邮件地址)并将匹配应用用户的声明(应用角色)添加到经过身份验证的用户身份(OpenID 身份)。

最后,我使用(自定义)AuthorizeAttribute(此处未显示)保护所有控制器操作,以确保经过身份验证的用户至少属于“用户”角色(如果不属于,则将它们重定向到“禁止访问”页面表示我们已经对他们进行了身份验证,但他们在系统中没有访问权限)。

【讨论】:

    【解决方案2】:

    OpenID 身份验证有效,但我不确定如何结合使用现有的 Identityuser / IdentityUserRole / RoleManager 管道。

    该应用程序非常依赖与这些用户关联的一些自定义数据,因此不能简单地使用 Active Directory 中的角色。

    根据您的要求,我假设您可以构建您的身份服务器(例如 IdentityServer3)并利用 IdentityServer3.AspNetIdentity 使用 ASP.NET Identity 进行身份管理。

    对于您的 Web 客户端应用程序,您可以使用 OpenID Connect 中间件并将授权设置为您的自定义身份服务器,并在您的身份服务器上设置您预先配置的 ClientId。

    此外,您可以关注此tutorial 以快速开始使用 IdentityServer3 和完整示例IdentityServer3 Samples。

    【讨论】:

      猜你喜欢
      • 2021-07-29
      • 1970-01-01
      • 1970-01-01
      • 2019-04-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多