(TL; DR:检查最近的更新)
第一个问题是,.net核心的不同版本之间的API有所更改。
第二个问题是,我在网上找到的每个示例都稍有不同,关于做什么是什么没有真正的权威性答案;相反,我一直在寻找“哦,更改对我有用的内容”的帖子,但是看起来像我一样的每个人都在尝试它,而不是完全了解。
无论如何,下面是代码:
Services.AddAuthentication(A =>
{
A.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
A.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(O =>
{
O.RequireHttpsMetadata = false;
O.SaveToken = true;
O.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(AuthJWTPublicKey)),
ValidateIssuer = false,
ValidateAudience = false
};
});
我有一个有效的JWT,但对控制器的任何调用都会导致立即错误401。
我试图用以下方式装饰控制器:
[授权]
[Authorize(Roles =“ offline_access”)]
[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme,角色=“ offline_access”)]
但没有运气
JWT的内容是:
{
"jti":"837c2dd1-cca5-491e-84a4-b17429366df5",
"exp":1558355152,
"nbf":0,
"iat":1558354852,
"iss":"xxxx",
"aud":"account",
"sub":"4ed1c313-c692-44db-86d3-7605f3e2c2c1",
"typ":"Bearer",
"azp":"test-app",
"auth_time":1558354850,
"session_state":"e40c9a95-ae8a-4d6e-b2a4-ad5e833867ea",
"acr":"1",
"realm_access":{
"roles":[
"offline_access",
"uma_authorization"
]
},
"resource_access":{
"account":{
"roles":[
"manage-account",
"manage-account-links",
"view-profile"
]
}
},
"scope":"openid email profile",
"email_verified":true,
"name":"firstd6d05 last29954",
"preferred_username":"xxxx",
"given_name":"firstd6d05",
"family_name":"last29954",
"email":"xxxx",
"group":[
"/Administrators"
]
}
我的目标纯粹是验证JWT的签名(并最终证明它已过期)并可以访问控制器中的令牌。
我正在将JWT通过标头,位于“授权”下,并且令牌前面带有文本“承载”。
我想念什么?
按照以下答案,我进行了以下更改:
我添加了:
Services.AddTransient<IClaimsTransformation, ClaimsTransformer>();
,然后在休息时添加以下类
internal class ClaimsTransformer : IClaimsTransformation
{
public Task<ClaimsPrincipal> TransformAsync(ClaimsPrincipal principal)
{
Debugger.Break();
}
}
但是我仍然收到带有Keycloak令牌的401;因此看起来它没有被拒绝之前就到达了索赔转换器。
我添加了ASP的调试输出。
它位于:https://pastebin.com/qvGsQG6j
相关的部分似乎是:
info: Microsoft.AspNetCore.Authorization.DefaultAuthorizationService[2]
=> ConnectionId:0HLN4CPASJL8F => RequestId:0HLN4CPASJL8F:00000001 RequestPath:/helpers/log => Test.WebControllers.HelpersController.GetLog (Test)
Authorization failed.
Microsoft.AspNetCore.Authorization.DefaultAuthorizationService:Info:Authorization failed.
Microsoft.AspNetCore.Authorization.DefaultAuthorizationService:Info:Authorization failed.
info: Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker[3]
=> ConnectionId:0HLN4CPASJL8F => RequestId:0HLN4CPASJL8F:00000001 RequestPath:/helpers/log => Test.WebControllers.HelpersController.GetLog (Test)
Authorization failed for the request at filter 'Microsoft.AspNetCore.Mvc.Authorization.AuthorizeFilter'.
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker:Info:Authorization failed for the request at filter 'Microsoft.AspNetCore.Mvc.Authorization.AuthorizeFilter'.
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker:Info:Authorization failed for the request at filter 'Microsoft.AspNetCore.Mvc.Authorization.AuthorizeFilter'.
info: Microsoft.AspNetCore.Mvc.ChallengeResult[1]
=> ConnectionId:0HLN4CPASJL8F => RequestId:0HLN4CPASJL8F:00000001 RequestPath:/helpers/log => Test.WebControllers.HelpersController.GetLog (Test)
此特定行可能会解释该问题:
针对过滤器'Microsoft.AspNetCore.Mvc.Authorization.AuthorizeFilter'的请求的授权失败
但是“失败”在我看来有点模糊。
最后一次测试:
我有这个令牌:
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ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wZrDMrbRiTBPSifCIBs3rxLQaL207blg+kj+EVLED5fZSOBlOyTOYQIDAQAB
它解码为(经jwt.io测试):
{
"http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name": "my name",
"http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress": "no@email.com",
"http://schemas.microsoft.com/ws/2008/06/identity/claims/expiration": "05/31/2019 00:13:20",
"http://schemas.xmlsoap.org/ws/2005/05/identity/claims/sid": "7cacf7b5-8669-469e-9885-d4804f28cc4a",
"http://schemas.xmlsoap.org/ws/2009/09/identity/claims/actor": "d2f6b724-a4f9-4bdd-a647-4d3e1a5968de",
"nbf": 1559175200,
"exp": 1559261600,
"iss": "test",
"aud": "test-app"
}
它是由以下代码生成的:
var Expiration = DateTime.UtcNow + TimeSpan.FromDays(1);
var Identity = new ClaimsIdentity(new[]
{
new Claim(ClaimTypes.Name, "my name"),
new Claim(ClaimTypes.Email, "no@email.com"),
new Claim(ClaimTypes.Expiration, Expiration.ToString(CultureInfo.InvariantCulture)),
new Claim(ClaimTypes.Sid, Guid.NewGuid().ToString()),
new Claim(ClaimTypes.Actor, Guid.NewGuid().ToString()),
});
var Token = new JwtSecurityToken
(
issuer: "test",
audience: "test-app",
claims: Identity.Claims,
notBefore: DateTime.UtcNow,
expires: Expiration,
signingCredentials: new SigningCredentials(new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_JwtRsaPublicKey)), SecurityAlgorithms.HmacSha256)
);
var TokenString = new JwtSecurityTokenHandler().WriteToken(Token);
return TokenString;
在asp中,我有以下代码:
Services.AddAuthentication(A =>
{
A.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
A.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(O =>
{
O.RequireHttpsMetadata = false;
O.SaveToken = true;
O.IncludeErrorDetails = true;
O.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(AuthJWTPublicKey)),
ValidateIssuer = false,
ValidateAudience = false
};
});
我有一个控制器方法,
[Authorize]
但是我一直得到401,无论我尝试什么,我都会得到401 ...
即使我将ValidateIssuerSigningKey设置为false。我得到401
设置为:
在ConfigureServices中,我有:
Services.AddMvc()
and the code above
在“配置”中,我有:
Application.UseAuthentication();
Application.UseMvc(Routes => { Routes.MapRoute("default_route", "{controller}/{action}/{id?}"); });
答案 0 :(得分:1)
public static class ClaimTypes { internal const string ClaimTypeNamespace ="http://schemas.microsoft.com/ws/2008/06/identity/claims"; .... public const string Role = ClaimTypeNamespace + "/role"; ...
常量 ClaimTypes.Role
是 http://schemas.microsoft.com/ws/2008/06/identity/claims/role
请注意,您的控制器需要使用offline_access
的角色:
[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme, Roles = "offline_access")]
换句话说,它期望已解码的JWT
具有 http://schemas.microsoft.com/ws/2008/06/identity/claims/role
属性来配置角色:
{ "nbf": ..., "exp": ..., "iss": ..., "aud": ..., ..., "http://schemas.microsoft.com/ws/2008/06/identity/claims/role": [ "offline_access", "...other roles" ], }
但是,您可以通过以下方式配置角色:
"realm_access":{
"roles":[
"offline_access",
"uma_authorization"
]
},
最简单的方法是重建令牌以配置offline_access
的角色:
ClaimsIdentity identity = new ClaimsIdentity(new[] {
new Claim(ClaimTypes.Name,"1024"),
new Claim(ClaimTypes.Role,"offline_access"),
new Claim(ClaimTypes.Role,"...other roles"),
// ... other claims
});
var token = new JwtSecurityToken
(
issuer: _issuer,
audience: _audience,
claims: identity.Claims,
expires: expiry,
notBefore: DateTime.UtcNow,
signingCredentials: new SigningCredentials(new SymmetricSecurityKey(Encoding.UTF8.GetBytes(mykeyname)),
SecurityAlgorithms.HmacSha256)
);
var tokenStr = tokenHandler.WriteToken(token);
或者您可以通过注册自定义IClaimsTransformation
将keycloak的样式声明转换为Microsoft的样式,请参阅ASP.NET Core Team https://github.com/aspnet/AspNetCore/blob/658b37d2bd3b0da2c07e25b53fa5c97ce8d656d3/src/Security/samples/ClaimsTransformation/Startup.cs#L34的示例
答案 1 :(得分:0)
我不确定变量中存储了什么,但看起来它不是私有令牌:
IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(AuthJWTPublicKey)),
据我所知,这是一个私有对称密钥,也许您在其中传递了错误的值?