如何在.net核心中替换AWS Cognito Oauth2的Claimsprincipal?

时间:2019-03-30 20:10:08

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

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

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

        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;
    }

有什么主意如何覆盖当前上下文。Principal.Identity而不是添加新上下文?

1 个答案:

答案 0 :(得分:0)

上下文中的<img id="image" src="localhost/1.jpg" style="width: 800px; height: 800px" /> <br /> <input type="button" value="Start Slide Show" onclick="startImageSlideShow()" /> <input type="button" value="Stop Slide Show" onclick="stopImageSlideShow()" /> <script type="text/javascript"> function stopImageSlideShow() { clearInterval(intervalId); } function setImage() { var imageSrc = document.getElementById("image").getAttribute("src"); var currentImageNumber = imageSrc.substring(imageSrc.lastIndexOf("/") + 1, imageSrc.lastIndexOf("/") + 2); if (currentImageNumber == 3) { currentImageNumber = 0; } document.getElementById("image").setAttribute("src", "http://localhost/" + (Number(currentImageNumber) + 1) + ".jpg"); } </script> 属性是可变的,因此将其替换为新属性。

13:06:35.277 INFO [ActiveSessions$1.onStop] - Removing session 70a1b8cbae6876cde7e66df13b3942d1 (org.openqa.selenium.chrome.ChromeDriverService)