【问题标题】:How to connect Asp.net core Identity user to IdentityServer4 user如何将 Asp.net core Identity 用户连接到 IdentityServer4 用户
【发布时间】:2020-07-06 06:15:26
【问题描述】:

我有一个 IdentityServer4 部署了一个支持 SQL 服务器数据库。 我还部署了一个 Asp.NET Core WebAppi 服务,它使用 IdentityServer4 作为权限。 然后我有一个 Typescrip SPA 客户端,它使用(目前)IdenityServer4 登录并获取 JWTToken 以连接到 WebAPI。

如何在 WebApi 上使用 Microsoft Indentity 来管理授权。我的意思是,现在当我向 IdentityServer 进行身份验证时,我在我的 WebApi 控制器中获得了一个用户对象。该用户与 IdentityServer4 绑定并拥有其声明。我想将此用户连接到我的 WebApi 中的本地 Asp.NEt 身份用户,这样我就可以管理它的角色并专门为此 WebApi 声明。

在 WebApi 上,我想使用 Microsoft asp.net 身份在本地存储用户、用户角色、特定于该 webApi 的用户声明,并且只使用 IdentityServer4 进行身份验证。如何将 IS4 用户映射到我的 Asp.NEt Core Identity 用户?

【问题讨论】:

    标签: asp.net-core authorization asp.net-core-webapi identityserver4


    【解决方案1】:

    虽然您可以从 IdentityServer 的 UserInfo 端点获取用户的角色,并执行与 Asp.Net Identity 相同的操作。

    所以,在所有令牌的验证操作之后,您必须检查用户是否存在于您的数据库中。如果不存在,则将用户添加到您的数据库。

            services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
    
            }).AddJwtBearer(options =>
            {
                options.Authority = "";
                options.RequireHttpsMetadata = false;
                options.Audience = "";
                options.Events.OnTokenValidated = async (context) =>
                {
                    var usermanager = services.BuildServiceProvider().GetService<UserManager<ApplicationUser>>();
                    var user = await usermanager.FindByNameAsync(context.HttpContext.User.Identity.Name);
    
                    if (user == null)
                    {
                        user = new ApplicationUser();
                        user.UserName = context.HttpContext.User.Identity.Name;
                        //...
    
                        await usermanager.CreateAsync(user);
                    }
                };
            });
    

    【讨论】:

    • 感谢您的快速响应。这正是我想要的。
    猜你喜欢
    • 2017-03-23
    • 2018-02-12
    • 2019-01-12
    • 2021-05-16
    • 1970-01-01
    • 1970-01-01
    • 2021-04-11
    • 2018-08-03
    • 2017-11-01
    相关资源
    最近更新 更多