簡體   English   中英

如何在.net核心中替換aws cognito Oauth2的Claimsprincipal?

[英]How can I replace Claimsprincipal for aws cognito Oauth2 in .net core?

我在我的asp.net核心MVC解決方案中嘗試了Aws Cognito。

我在我的啟動中注冊了Cookie-auth,並在OnCreatingTicket事件中添加了一個監聽器來解析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 core的AntiForgery系統所需要的。

解析jwt-token:

    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而不是添加一個新的?

上下文中的Principal屬性是可變的,因此請用新的替換它。

context.Principal = new ClaimsPrincipal(appIdentity);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM