繁体   English   中英

Asp .net Core 3.1 使用多个 AuthenticationScheme 转换 ClaimsIdentity

[英]Asp .net Core 3.1 transforming ClaimsIdentity with multiple AuthenticationScheme

在 ASP.Net Core 应用程序中实现几个授权方案时,我遇到了一个问题。 可以说它们在 Startup.cs 中是这样声明的

public void ConfigureServices(IServiceCollection services)
{
      AuthenticationBuilder builder = services
                .AddAuthentication()
                .AddBasicAuthentication(o => { o.Realm = "MyRealm"; })
                .AddApiKeyAuthentication()
                .AddBearerToken(opt => { });
}

这些方案中的每一个都提供了自己的AuthenticationHandler实现,如果成功则返回ClaimsIdentity 但在每种情况下,声明的结构都是不一致的,即 ApiKeyAuthentication 可能会返回ClaimsIdentity以及存储在声明“api_service”中的业务敏感数据,而 BearerTokenScheme 会将其存储在声明“sub”中,而我无法控制这一点。 因此,如果我想在 controller 中使用此信息来将某些进程与调用了我的 api 方法的服务相关联,我必须实现一些复杂的逻辑来分析当前的ClaimsIdentity 、其身份验证方案和声明集。 相反,我想实现某种将 ClaimsIdentity 转换为MyServiceClaimsIdentity的方式,这将以方便的方式公开声明,以便我可以在控制器代码中轻松使用它们:

public class MyServiceClaimsIdentity: IIdentity
{
    private readonly ClaimsIdentity innerIdentity;
    public Guid? UserId {get; }
    public string UserName {get; }
    public string ServiceName {get; }

    public MyServiceClaimsIdentity(ClaimsIdentity identity)
    {
        this.innerIdentity = identity;
        TransformClaimsIntoProperties();
    }

    private void TransformClaimsIntoProperties()
    {
        ......
    }
}

我试图实现某种“变革性” AuthenticationHandler ,它会在所有其他处理程序产生它们的 ClaimsIdentity 之后产生MyServiceClaimsIdentity

public class FinalAuthenticationHandler : AuthenticationHandler<FinalAuthenticationOptions>
    {
        public FinalAuthenticationHandler(
            IOptionsMonitor<FinalAuthenticationOptions> options,
            ILoggerFactory logger,
            UrlEncoder encoder,
            ISystemClock clock)
            : base(options, logger, encoder, clock)
        {
        }

        protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
        {
            if (!this.Context.User.Identity.IsAuthenticated)
            {
                return null;
            }

            var identity = new MyServiceClaimsIdentity(this.Context.User.Identity);
            var principal = new ClaimsPrincipal(identity);
            var ticket = new AuthenticationTicket(principal, this.Scheme.Name);
            return AuthenticateResult.Success(ticket);
        }
    }

在这一点上太糟糕了this.Context.User.Identity没有用户的任何信息,所以我很困惑将这个转换逻辑放在哪里,或者我将如何在我的 FinalAuthenticationHandler 中获得其他 Handler 提供的当前ClaimsIdentity 任何帮助,将不胜感激。

实施 IClaimsTransformation 并将其注册为 Singleton 做得很好

internal sealed class ClaimsTransformation : IClaimsTransformation
    {
        private readonly IDictionary<string, IClaimsHandler> handlersMap;

        public ClaimsTransformation(IEnumerable<IClaimsHandler> handlers)
        {
            if (handlers == null)
            {
                throw new ArgumentNullException(nameof(handlers));
            }

            this.handlersMap = handlers.ToDictionary(t => t.SchemeName);
        }

        public Task<ClaimsPrincipal> TransformAsync(ClaimsPrincipal principal)
        {
            if (!(principal.Identity is ClaimsIdentity claimsIdentity))
            {
                throw new InvalidOperationException($"Principal.Identity is of type {principal.Identity.GetType()}, expected ClaimsIdentity");
            }

            if (!this.handlersMap.TryGetValue(principal.Identity.AuthenticationType, out var handler))
            {
                throw new AuthenticationException($"Scheme of type {principal.Identity.AuthenticationType} is not supported");
            }

            var result = new ClaimsPrincipal(handler.Handle(claimsIdentity));
            return Task.FromResult(result);
        }
    }

暂无
暂无

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

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