繁体   English   中英

Asp.Net Identity 2 用户信息如何映射到 IdentityServer3 配置文件声明

[英]How does Asp.Net Identity 2 User Info get mapped to IdentityServer3 profile claims

我已经通过 Dapper 通过 SQL Server 支持的自定义用户存储设置并运行了 Asp.Net Identity 2。 此时在我的开发/测试中,我只关心本地帐户(但会添加外部登录提供程序)。 我有一个自定义用户,其中包含 Asp.Net Identity 想要的标准属性,并添加了一些我自己的(名字、姓氏):

public class AppUser : IUser<Guid>
{
    public Guid Id { get; set; }
    public string UserName { get; set; }
    public string PasswordHash { get; set; }
    public string SecurityStamp { get; set; }
    public string Email { get; set; }
    public bool EmailConfirmed { get; set; }
    public bool LockoutEnabled { get; set; }
    public DateTimeOffset LockoutEndDate { get; set; }
    public int AccessFailedCount { get; set; }

    // Custom User Properties
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

在我的 MVC Web 应用程序中,我像这样配置 OIDC:

       app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
        {
            Authority = ConfigurationManager.AppSettings["OpenIdConnectAuthenticationOptions.Authority"],
            ClientId = "MVC.Web",
            Scope = "openid profile email",
            RedirectUri = ConfigurationManager.AppSettings["OpenIdConnectAuthenticationOptions.RedirectUri"],
            ResponseType = "id_token",
            SignInAsAuthenticationType = "Cookies"
        });

由于我将profile包含为请求的范围,因此我得到:

preferred_username: testuser

由于我将email作为请求范围包括在内,我得到:

email:          user@test.com
email_verified: true

我没有明确告诉我的AspNetIdentityUserService如何将AspNetIdentityUserServiceUserName属性AppUserpreferred_username声明,我不确定这是如何发生的。 因此,我不明白如何将FirstName属性映射到given_name声明,以便它将与id_token一起返回。

我研究的内容:

因此,如果您在这里查看IdentityServer3 AspNetIdentity 示例,我发现这个ClaimsIdentityFactory看起来应该可以解决问题:

    public override async Task<ClaimsIdentity> CreateAsync(UserManager<User, string> manager, User user, string authenticationType)
    {
        var ci = await base.CreateAsync(manager, user, authenticationType);
        if (!String.IsNullOrWhiteSpace(user.FirstName))
        {
            ci.AddClaim(new Claim("given_name", user.FirstName));
        }
        if (!String.IsNullOrWhiteSpace(user.LastName))
        {
            ci.AddClaim(new Claim("family_name", user.LastName));
        }
        return ci;
    }

所以我将它添加到我的应用程序中并将它连接到我的自定义UserManager 当类被实例化时,我确实遇到了一个断点,但我从来没有在CreateAsync方法上遇到过断点,我的声明也没有返回。

我还在这里看到了这个IdentityServer3 自定义用户示例,我发现这个GetProfileDataAsync方法看起来可能是正确的(但对于看似如此简单/常见的事情,我似乎比我应该挖掘的更深入):

    public override Task GetProfileDataAsync(ProfileDataRequestContext context)
    {
        // issue the claims for the user
        var user = Users.SingleOrDefault(x => x.Subject == context.Subject.GetSubjectId());
        if (user != null)
        {
            context.IssuedClaims = user.Claims.Where(x => context.RequestedClaimTypes.Contains(x.Type));
        }

        return Task.FromResult(0);
    }

我在这里遇到了同样的问题,因为此方法中的断点从未被触发。 我什至查看了 IdentityServer3 源代码,发现只有在范围设置了IncludeAllClaimsForUser标志时才会调用它。 但是我在这里使用标准profile范围,所以我开始质疑是否需要为设置了IncludAllClaimsForUser标志的配置文件范围定义自己的定义,或者是否有办法将该标志添加到标准范围。

并添加到所有这些......这仅需要在使用本地帐户时完成。 当我实现外部登录提供程序时,我会在那里询问配置文件,并希望能够获得名字和姓氏。 所以我想知道一旦我已经得到这些声明(或者如何确定我是否需要从我的用户存储中提取它们)会发生什么。 似乎我需要连接到仅在进行本地登录时运行的东西。

然后我开始真正质疑我是否以正确的方式解决这个问题,因为我看到/找到的信息很少(我原以为这是其他人已经实施的相当普遍的情况,并希望查找文档/示例)。 一直试图解决这个问题一天了。 希望有人有一个快速的答案/指针!

我使用OpenIdConnectAuthenticationNotifications来实现这一点,您可以连接到 ASP.NET Identity 数据库或在其中执行任何操作,这是我用于我的项目之一的示例代码:

这是来自我的 Startup.cs 的完整源代码,但您真正需要的只是SecurityTokenValidated部分......

using System.Configuration;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Threading.Tasks;
using System.Web.Helpers;
using IdentityServer3.Core;
using Microsoft.IdentityModel.Protocols.OpenIdConnect;
using Microsoft.Owin.Security;
using Microsoft.Owin.Security.Cookies;
using Microsoft.Owin.Security.OpenIdConnect;
using Owin;

namespace MyProject
{
    public partial class Startup
    {
        public static string AuthorizationServer => ConfigurationManager.AppSettings["security.idserver.Authority"];

        public void ConfigureOAuth(IAppBuilder app)
        {
            AntiForgeryConfig.UniqueClaimTypeIdentifier = Constants.ClaimTypes.Subject;

            var jwtSecurityTokenHandler = new JwtSecurityTokenHandler();
            jwtSecurityTokenHandler.InboundClaimTypeMap.Clear();

            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = "Cookies"
            });

            app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
            {
                SecurityTokenValidator = jwtSecurityTokenHandler,
                Authority = AuthorizationServer,
                ClientId = ConfigurationManager.AppSettings["security.idserver.clientId"],
                PostLogoutRedirectUri = ConfigurationManager.AppSettings["security.idserver.postLogoutRedirectUri"],
                RedirectUri = ConfigurationManager.AppSettings["security.idserver.redirectUri"],
                ResponseType = ConfigurationManager.AppSettings["security.idserver.responseType"],
                Scope = ConfigurationManager.AppSettings["security.idserver.scope"],
                SignInAsAuthenticationType = "Cookies",
#if DEBUG
                RequireHttpsMetadata = false,   //not recommended in production
#endif
                Notifications = new OpenIdConnectAuthenticationNotifications
                {
                    RedirectToIdentityProvider = n =>
                    {
                        if (n.ProtocolMessage.RequestType == OpenIdConnectRequestType.Logout)
                        {
                            var idTokenHint = n.OwinContext.Authentication.User.FindFirst("id_token");

                            if (idTokenHint != null)
                            {
                                n.ProtocolMessage.IdTokenHint = idTokenHint.Value;
                            }
                        }

                        return Task.FromResult(0);
                    },

                    SecurityTokenValidated = n =>
                    {
                        var id = n.AuthenticationTicket.Identity;

                        //// we want to keep first name, last name, subject and roles
                        //var givenName = id.FindFirst(Constants.ClaimTypes.GivenName);
                        //var familyName = id.FindFirst(Constants.ClaimTypes.FamilyName);
                        //var sub = id.FindFirst(Constants.ClaimTypes.Subject);
                        //var roles = id.FindAll(Constants.ClaimTypes.Role);

                        //// create new identity and set name and role claim type
                        var nid = new ClaimsIdentity(
                            id.AuthenticationType,
                            Constants.ClaimTypes.Name,
                            Constants.ClaimTypes.Role);

                        nid.AddClaims(id.Claims);
                        nid.AddClaim(new Claim("id_token", n.ProtocolMessage.IdToken));
                        nid.AddClaim(new Claim("access_Token", n.ProtocolMessage.AccessToken));

                        ////nid.AddClaim(givenName);
                        ////nid.AddClaim(familyName);
                        ////nid.AddClaim(sub);
                        ////nid.AddClaims(roles);

                        ////// add some other app specific claim
                        // Connect to you ASP.NET database for example
                        ////nid.AddClaim(new Claim("app_specific", "some data"));

                        //// keep the id_token for logout
                        //nid.AddClaim(new Claim("id_token", n.ProtocolMessage.IdToken));

                        n.AuthenticationTicket = new AuthenticationTicket(
                            nid,
                            n.AuthenticationTicket.Properties);

                        return Task.FromResult(0);
                    }
                }
            });

            //app.UseResourceAuthorization(new AuthorizationManager());
        }
    }
}

这个问题的 (A) 正确答案是覆盖AspNetIdentityUserService类中的GetProfileDataAsync方法,如下AspNetIdentityUserService

public class AppUserService : AspNetIdentityUserService<AppUser, Guid>
{
    private AppUserManager _userManager;

    public AppUserService(AppUserManager userManager)
        : base(userManager)
    {
        _userManager = userManager;
    }

    public async override Task GetProfileDataAsync(ProfileDataRequestContext ctx)
    {
        var id = Guid.Empty;
        if (Guid.TryParse(ctx.Subject.GetSubjectId(), out id))
        {
            var user = await _userManager.FindByIdAsync(id);
            if (user != null)
            {
                var claims = new List<Claim>
                {
                    new Claim(Constants.ClaimTypes.PreferredUserName, user.UserName),
                    new Claim(Constants.ClaimTypes.Email, user.Email),
                    new Claim(Constants.ClaimTypes.GivenName, user.FirstName),
                    new Claim(Constants.ClaimTypes.FamilyName, user.LastName)
                };
                ctx.IssuedClaims = claims;
            }
        }
    }
}

但正如我所发现的,这还不够。 查看 IdentityServer源代码,你会发现这一点:

        if (scopes.IncludesAllClaimsForUserRule(ScopeType.Identity))
        {
            Logger.Info("All claims rule found - emitting all claims for user.");

            var context = new ProfileDataRequestContext(
                subject,
                client,
                Constants.ProfileDataCallers.ClaimsProviderIdentityToken);

            await _users.GetProfileDataAsync(context);

            var claims = FilterProtocolClaims(context.IssuedClaims);
            if (claims != null)
            {
                outputClaims.AddRange(claims);
            }

            return outputClaims;
        }

请注意,除非设置了一个标志以包含所有声明, GetProfileDataAsync不会调用GetProfileDataAsync (不确定他们为什么选择这样做,但显然必须有充分的理由!)。 所以我认为这意味着我需要完全重新定义profile范围,但是通过进一步挖掘源代码,我发现情况并非如此。 StandardScopes 有一个方法可以创建带有 always include 标志 set 的范围 而不是设置你的范围这样做:

        factory.UseInMemoryScopes(StandardScopes.All);

做这个:

        factory.UseInMemoryScopes(StandardScopes.AllAlwaysInclude);

然后您的GetProfileDataAsync将运行,您将获得所有声明!

注意:我第一次尝试使用ClaimsIdentityFactory并没有成功,因为我没有登录到 Asp.Net Identity,而且除非我这样做,否则它永远不会被调用是有道理的。

注意:@Rosdi Kasim 的回答如果您希望在已经从 Identity Server 收到您的 id_token 之后添加声明(尤其是应用程序特定声明)当然是有效的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM