Complex claims in JWT

2019-06-21 13:10发布

The JWT RFC does not seem to have any problem containing complex arrays such as:

{
    "email": "test@test.com",
    "businesses": [
        {
            "businessId": "1",
            "businessName": "One",
            "roles": [
                  "admin",
                  "accountant"
            ]
        },
        {
            "businessId": "2",
            "businessName": "Two",
            "roles": [
                  "support"
            ]
        }
     ]
}

And this seems a desirable scenario for our needs, since as part of the token we'd like to have a list of businesses a user has access to and what roles does he have for each business (it's part of its identity). The authorization policies at the API would later understand those groups and apply the required authorization logic.

I have seen that with IdentityServer4 the claims are added to the ProfileDataRequestContext's IEnumerable<Claim> IssuedClaims property.

Is there any recommended alternative to this complex claim structure? If not, is there any way to build that structure with IdentityServer4 (maybe some extension?) or the only way would be to manually serialize the JSON since the Claim seems to accept only a string?

PS: I have seen this question and this other where one of the authors of Identity Server talks about something similar being an antipattern. Not sure if the antipattern would be to have complex claims' structure or "authorization implementation details" in the claims.

Any advice on this would be great!

UPDATE:

After giving some thoughts I agree having a complex hierarchy of claims is not desirable and I could go around this problem with a dirty solution of prefixing roles for each businessId. Something like this:

{
    "email": "test@test.com",
    "roles": [
        "1_admin",
        "1_accountant",
        "2_support"
     ],
     "businesses": [
        "1_One",
        "2_Two" 
     ]
}

that way I keep a simple structure and later on, at the client or API I can read the claims and find out that 1 is the id for the business with name One and it has the roles admin and account.

Would this be a better solution?

1条回答
闹够了就滚
2楼-- · 2019-06-21 13:28

Claims are about identity information - and not complex permission "objects". You are far better off with a dedicated permission service that returns your permissions in any format you want based on the identity of the user.

I also hope your permission data doesn't change while the token is being used, otherwise you end up with stale data.

That said - claims are always strings in .NET - but you can serialize JSON objects into it by setting the ClaimValueType to IdentityServerConstants.ClaimValueTypes.Json.

查看更多
登录 后发表回答