dylanplecki / KeycloakOwinAuthentication

Keycloak Authentication Middleware for the C# OWIN Pipeline
http://keycloak.jboss.org
MIT License
56 stars 130 forks source link

map global realm roles to claim #34

Open ahus1 opened 8 years ago

ahus1 commented 8 years ago

I have some global realm roles, see JWT excerpt below. I found that Keycloak Owin did not map them. This is the code I needed to add to make it working.

Both types of roles are mapped to ClaimTypes.Role. This works for me, but I don't know if there is a better possibility to do this.

Best regards, Alexander

{
...
  "realm_access": {
    "roles": [
      "my-role-1",
      "my-role-2"
    ]
  },
...
}
ntheile commented 8 years ago

We might have to think about this one. There could be the possibility that you could end up having duplicate roles. For example if you had this jwt:

"realm-management": {
    "roles": [
        "realm-admin"
      ]
    },
"myapp": {
      "roles": [
        "realm-admin"
      ]
    }

The ClaimsPricipal roles would look like this:

1. http://schemas.microsoft.com/ws/2008/06/identity/claims/role: realm-admin
2. http://schemas.microsoft.com/ws/2008/06/identity/claims/role: realm-admin`

As an alternate appraoch to your code above,we do pass back the access_token in the Claims, so you can simply get this information currently by decoding the jwt like this:

var me = User as ClaimsPrincipal;
string token = me.Claims.FirstOrDefault(c => c.Type == "access_token").Value;
JwtSecurityToken tokenParsed = new JwtSecurityToken(token);
var globalRoles = tokenParsed.Claims.Where(c => c.Type == "resource_access");