Reputation: 12127
(TL;DR: check the last update)
The first issue with this is that the API has changed between the different versions of .net core.
The second one is that every example I find online is slightly different with not real authoritative answer as to what does what; rather I keep finding posts with 'oh, changing this worked for me', but it looks like everyone is, like me, experimenting with it rather than having a full understanding.
Anyhow, here is the code:
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
};
});
I have a valid JWT but any call to my controller results in an immediate error 401.
I have tried to decorate the controller with:
[Authorize]
[Authorize(Roles = "offline_access")]
[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme, Roles = "offline_access")]
but no luck
The JWT content is:
{
"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"
]
}
My goal is purely to verify the signature of the JWT (and eventually it's expiration) and have access to the token in the controller.
I am passing the JWT through the header, under 'Authorization' and with the text 'Bearer' in front of the token.
What am I missing?
Following the answer below, I did the following change:
I added:
Services.AddTransient<IClaimsTransformation, ClaimsTransformer>();
and then added the following class with a break
internal class ClaimsTransformer : IClaimsTransformation
{
public Task<ClaimsPrincipal> TransformAsync(ClaimsPrincipal principal)
{
Debugger.Break();
}
}
but I am still getting a 401 with the Keycloak token; so it looks like it doesn't get to the claims transformer before being rejected.
I added the debug output of ASP.
It is at: https://pastebin.com/qvGsQG6j
The relevant part seems to be:
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)
This specific line may explain the issue:
Authorization failed for the request at filter 'Microsoft.AspNetCore.Mvc.Authorization.AuthorizeFilter'
but 'failed' seems a bit vague to me.
Last test:
I have this token:
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJodHRwOi8vc2NoZW1hcy54bWxzb2FwLm9yZy93cy8yMDA1LzA1L2lkZ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AQAB
it decodes to (as tested by 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"
}
it is generated by the following code:
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;
In asp, I have the following code:
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
};
});
and I have a controller method with:
[Authorize]
But I keep getting a 401, no matter what I try, I get a 401...
Even if I set ValidateIssuerSigningKey to false. I get a 401
The setup is:
In ConfigureServices, I have:
Services.AddMvc()
and the code above
In Configure, I have:
Application.UseAuthentication();
Application.UseMvc(Routes => { Routes.MapRoute("default_route", "{controller}/{action}/{id?}"); });
Upvotes: 1
Views: 1147
Reputation: 357
You can modify keycloak configuration for JWT creation to map the roles to "roles" item instead grouping under "realm_access".
This can be done by adding a Mapper in Keycloak client.
This works for me:
You can also create a second Mapper for "User Client Role". Just select "User Client Role" for Mapper Type.
Upvotes: 0
Reputation: 30355
I am not sure what is stored in the variable but it looks like it's not a private token:
IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(AuthJWTPublicKey)),
This is as far as I know a private symmetric key, perhaps you are passing a wrong value in there?
Upvotes: 0
Reputation: 25380
According to dotnet/corefx:
public static class ClaimTypes { internal const string ClaimTypeNamespace ="http://schemas.microsoft.com/ws/2008/06/identity/claims"; .... public const string Role = ClaimTypeNamespace + "/role"; ...
The const ClaimTypes.Role
is http://schemas.microsoft.com/ws/2008/06/identity/claims/role
Note your controller requires a role of offline_access
:
[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme, Roles = "offline_access")]
In other words, it expects the decoded JWT
has a property of http://schemas.microsoft.com/ws/2008/06/identity/claims/role
to configure the roles:
{ "nbf": ..., "exp": ..., "iss": ..., "aud": ..., ..., "http://schemas.microsoft.com/ws/2008/06/identity/claims/role": [ "offline_access", "...other roles" ], }
However, you configure the roles in the following way:
"realm_access":{
"roles":[
"offline_access",
"uma_authorization"
]
},
The easiest way is rebuild the token to config a role of 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);
Or you could transform the keycloak's style claim to Microsoft's style by registering a custom IClaimsTransformation
, see a Sample by ASP.NET Core Team https://github.com/aspnet/AspNetCore/blob/658b37d2bd3b0da2c07e25b53fa5c97ce8d656d3/src/Security/samples/ClaimsTransformation/Startup.cs#L34
Upvotes: 2