#c# #asp.net-core #amazon-cognito
#c# #asp.net-core #amazon-cognito
Вопрос:
Я пробую Aws Cognito в моем asp.net основное MVC-решение.
Я регистрирую Cookie-auth в своем автозагрузке и добавляю прослушиватель к OnCreatingTicket-событию для анализа 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
};
});
Однако я смог найти только принципала.AddIdentity-метод, который позволяет мне добавить новый ClaimsIdentity, но я хочу заменить текущий идентификатор, поскольку это необходимо для asp.net система защиты от подделок в ядре.
Анализ 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.Идентификатор вместо добавления нового?
Ответ №1:
Principal
Свойство в контексте изменяемо, поэтому замените его новым.
context.Principal = new ClaimsPrincipal(appIdentity);