Claims Transformation in .NET 6
--
OAuth2 is a great protocol to authenticate people. And it does just that: Authentication. So.. What about authorization?
Implementing authorization in an API is pretty straightforward. And there are several ways to do it. In many projects, authorization and business logic tend to get mixed up. As a result, the code of the average, simple API endpoint gets more complex. And as a result, features get harder to implement and the application becomes less secure. So, needless to say: Don’t mix the two. But how do you do that?
To authorize means to apply a policy to a person in the context of him/her trying to access a resource. To be able to apply a policy that makes sense in your business context, you’ll probably need relevant domain-specific information about the person. But an access_token doesn’t contain that information by default. So, assuming we don’t want to put that information in the token, where do we put that? And how would that work?
Default claims you can use for authorization
When a user has authenticated and invokes an API endpoint with his/her access token, ASP.NET turns the token into a ClaimsIdentity. This ClaimsIdentity is available in your controller when you type:
Claims transformation
Say you are offering a SaaS product online. You would likely want to authorize someone based on his or her license. But, as you can see, such information is not available in the default claims.
Microsoft has support for this scenario out of the box. You can enrich claims on the fly (as you can read here). This concept is known as claims transformation. (In previous versions of .NET, this concept was known as claims augmentation.)
When you’re applying claims transformation, this is what the process of authenticating and authorizing looks like:
There are several challenging bits in this diagram. This article focuses on parts 3 and 4.