【问题标题】:How can I replace Claimsprincipal for aws cognito Oauth2 in .net core?如何在 .net 核心中为 aws cognito Oauth2 替换 Claimsprincipal?
【发布时间】:2019-03-31 15:59:53
【问题描述】:

我正在我的 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-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 而不是添加一个新的?

【问题讨论】:

    标签: c# asp.net-core amazon-cognito


    【解决方案1】:

    上下文中的Principal 属性是可变的,因此请将其替换为新的。

    context.Principal = new ClaimsPrincipal(appIdentity);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-01-01
      • 2018-04-02
      • 2022-10-13
      • 2020-09-30
      • 1970-01-01
      • 2018-01-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多