c# - 如何在 .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 而不是添加一个新的?
解决方案
上下文的Principal
属性是可变的,所以用一个新的替换它。
context.Principal = new ClaimsPrincipal(appIdentity);
推荐阅读
- python - 为什么在 google colab 中出现名称错误?
- vba - 通过 VBA 访问添加到现有的直通查询
- android - 如何在 Compose 应用程序中请求权限?
- android - 需要将Adapter绑定到RecyclerView两次才能出现数据
- r - 使用 R Markdown 将 xls 文件加载到 R 时出现问题
- javascript - 为什么我不能使用左手赋值来修改函数结果的值?
- mongodb - 按对象数组对文档进行分组
- python - 使用 Pandas 的平均平均时间列 h:MM:SS CSV
- graphql - AppSync:无法转换为对象
- python - 无法从 Pycharm 中的 pychon 控制台运行,但可以运行脚本