【发布时间】:2019-08-17 07:28:17
【问题描述】:
我正在尝试在 .Net Core MVC 应用程序中使用 AWS Cognito 进行身份验证。
登录工作正常,但视图中的任何表单都不起作用,它们都给出了关于我的声明不包含“名称”-声明的错误。
我尝试手动添加名称声明,但仍然抛出错误。
你知道如何在 .net core 中配置它吗?
错误信息:
InvalidOperationException:提供的“System.Security.Claims.ClaimsIdentity”类型标识标记为 IsAuthenticated = true,但没有 Name 值。默认情况下,防伪系统要求所有经过身份验证的身份都具有唯一的名称。如果无法为此身份提供唯一名称,请考虑通过覆盖 DefaultAntiforgeryAdditionalDataProvider 或可为当前用户提供某种形式的唯一标识符的自定义类型来扩展 IAntiforgeryAdditionalDataProvider。
启动配置:
services.AddAuthentication(options =>
{
//Sets Default Scheme.
options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
//Must match the string for AddOAuth to set OAuth as default Challenge Scheme.
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://myauth.auth.eu-west-1.amazoncognito.com/oauth2/authorize";
options.TokenEndpoint = "https://myauth.auth.eu-west-1.amazoncognito.com/oauth2/token";
options.SaveTokens = true;
options.ClaimsIssuer = "https://cognito-idp.eu-west-1.amazonaws.com/ID";
options.Events = new OAuthEvents
{
//Adds Cognito id_token to Claims.
OnCreatingTicket = OnCreatingTicket
};
});
手动添加名称标识符:
private static Task OnCreatingTicket(OAuthCreatingTicketContext context)
{
var handler = new JwtSecurityTokenHandler();
//Cognito stores user information and Claims in the id_token.
var idToken = context.TokenResponse.Response["id_token"];
var jwtToken = handler.ReadJwtToken(idToken.ToString());
var appIdentity = new ClaimsIdentity(jwtToken.Claims);
foreach (var item in appIdentity.Claims)
{
if (item.Type == "sub")
{
var name = new Claim("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier", item.Value);
var name2 = new Claim("http://schemas.microsoft.com/accesscontrolservice/2010/07/claims/identityprovider", item.Value);
appIdentity.AddClaim(name);
appIdentity.AddClaim(name2);
break;
}
}
context.Principal.AddIdentity(appIdentity);
return Task.CompletedTask;
}
【问题讨论】:
-
也许这会有所帮助? joonasw.net/view/adding-custom-claims-aspnet-core-2 还有,也许你只需要
add new Claim("Name", item.Value) -
也试过了,不确定它在寻找什么,但它不是“名称”。
标签: asp.net-mvc asp.net-core .net-core asp.net-core-mvc asp.net-core-2.0