【问题标题】:How to use IdentityServer4 to authenticate local user from local database?如何使用 IdentityServer4 从本地数据库对本地用户进行身份验证?
【发布时间】:2020-01-24 09:54:08
【问题描述】:

我正在为多个现有项目创建 SSO 解决方案。大多数应用程序已经使用相同的数据库,所以相同的用户和我在 IdentityServer 中使用这些用户。但是有一个应用程序有自己的用户数据库和登录屏幕。此表中的用户用于此应用 (FK) 中的一个表中。

我的想法是让现有用户数据库保持原样。将列 MasterUserGuid 添加到 Users 表中,该表将包含“主”用户 Guid(即 IdentityServer 用于身份验证的用户)并实现以下流程:

  1. 用户打开应用但未登录
  2. 用户被重定向到 IdentityServer 并使用全局凭据
  3. 用户被重定向回应用程序,该应用程序从声明中获取全局用户 GUID 并验证本地用户(在 MasterUserGuid 列中使用此 GUID),而不是使用全局用户

问题是我不知道如何实现步骤3,或者在 IdentityServer4 中是否可能/支持它。目前我被重定向到 IdentityServer,经过身份验证并被重定向回来,但随后应用程序尝试使用此外部用户。

在研究时,我读到用户应该在一个表中,所以这种方法可能是完全错误的,最好删除本地用户并打破提到的表的 FK 并手动迁移用户。

我提供的步骤中描述的场景是否可行且合理?

【问题讨论】:

  • 首先,您的一个应用是什么?是 ASP.NET 经典(owin),ASP.NET Core,它使用 MS Identity FW 访问数据库吗?
  • 它是使用 EntityFramework 的 ASP.NET Core MVC。目前它使用Microsoft.AspNet.Identity 对此本地数据库进行身份验证。
  • 据我所见(我还没有编写这个应用程序)AspNet.Identity 使用相同的上下文(app.CreatePerOwinContext<ApplicationUserManager>((options, context) => ApplicationUserManager.Create(context.Get<ModelEntities>())); 其中ModelEntities 是 EF 上下文类。Identity 使用数据库中的标准表集( AspNetRolesAspNetUsers 等)在上下文中未映射为 IDbSets。
  • 我现在在想,解决方案可能是让用户通过全局用户进行身份验证,但查找并覆盖使用 UserID 的位置,以使用映射列和本地用户 ID 而不是全局一。我现在检查一下这在代码中是否有意义。
  • 首先我会摆脱 AspNet.Identity。然后在AddAuthentication.AddOpenIdConnect 调整本地令牌以保留您喜欢的任何内容作为主要身份(在应用程序内)

标签: asp.net-core entity-framework-core asp.net-identity identityserver4


【解决方案1】:

您需要先调整您的应用程序以通过 IdentityServer 进行身份验证。删除所有与注册、登录等相关的 ASP.NET Core 身份逻辑,假设所有这些都将在 IdentityServer 端完成。然后实现IClaimsTransformation 的实例,它将替换您当前的ClaimsPrincipal,或者在需要时使用您想要的声明值(从本地数据库填充)添加其他身份。示例如下:

public class MyClaimsTransformer : IClaimsTransformation
{
    public Task<ClaimsPrincipal> TransformAsync(ClaimsPrincipal principal)
    {
        var claims = new List<Claim>();
        claims.Add(new Claim(...)); // put here your claim type and value

        var identity = new ClaimsIdentity(claims);
        principal.AddIdentity(identity);
        return principal;
    }
}

然后在 Startup.ConfigureServices 方法中在 IOC 中注册您的索赔转换器:

services.AddTransient<IClaimsTransformation, MyClaimsTransformer>();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-12-09
    • 2011-06-28
    • 1970-01-01
    • 2011-04-04
    • 2016-08-20
    • 2011-07-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多