首页 > 解决方案 > 如何在 .net 核心中为 aws cognito Oauth2 替换 Claimsprincipal?

问题描述

我在我的 asp.net 核心 MVC 解决方案中试用 Aws Cognito。

我在启动时注册了 Cookie-auth 并向 OnCreatingTicket-event 添加了一个侦听器,以解析我在成功登录后获得的 JWT-token,如下所示:

        services.AddAuthentication(options =>
        {
            options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            options.DefaultChallengeScheme = "Cognito";
        })
           .AddCookie()
           .AddOAuth("Cognito", options =>
           {
               options.ClientId = Configuration["Authentication:Cognito:ClientId"];
               options.ClientSecret = Configuration["Authentication:Cognito:Secret"];
               options.CallbackPath = new PathString("/sign-in");
               options.AuthorizationEndpoint = "https://xx.auth.eu-west-1.amazoncognito.com/oauth2/authorize";
               options.TokenEndpoint = "https://xx.auth.eu-west-1.amazoncognito.com/oauth2/token";
               options.SaveTokens = true;
               options.ClaimsIssuer = "https://cognito-idp.eu-west-1.amazonaws.com/xxx";

               options.Events = new OAuthEvents
               {
                    OnCreatingTicket = OnCreatingTicket
               };
           }); 

但是我只能找到 Principal.AddIdentity 方法,它可以让我添加新的 CLaimsIdentity,但我想要的是替换当前的身份,因为这是 asp.net 核心的 AntiForgery 系统所需要的。

解析 jwt 令牌:

    private static Task OnCreatingTicket(OAuthCreatingTicketContext context)
    {
        var handler = new JwtSecurityTokenHandler();

        var idToken = context.TokenResponse.Response["id_token"];
        var jwtToken = handler.ReadJwtToken(idToken.ToString());

        var appIdentity = new ClaimsIdentity(jwtToken.Claims);

//how to override context.Principal?
        context.Principal.AddIdentity(appIdentity);

        return Task.CompletedTask;
    }

任何想法如何覆盖当前的 context.Principal.Identity 而不是添加一个新的?

标签: c#asp.net-coreamazon-cognito

解决方案


上下文的Principal属性是可变的,所以用一个新的替换它。

context.Principal = new ClaimsPrincipal(appIdentity);

推荐阅读