Before we get in to the solution of how we can handle multiple token issuer, I’m going to bring up some of the fundamentals of how HTTP request/Response is handler to make a lot of sense out of the proposed solution.
Whenever a HTTP request is made, the call goes through the HTTP message handler and returns the HTTP response. HttpMessageHandler abstract class is the base class for message Handler.
I sniped the above picture form here which clearly explains how Message Handlers can be hooked inside the pipeline. As we notice, we can have multiple such custom message handler which we can chain it together. The first handler receives an HTTP request, does some processing, and gives the request to the next handler. At some point, the response is created and goes back up the chain. This pattern is called a delegating handler.
Our solution to go handle multiple token issuers is entirely based on HTTP MessageHandlers. We inherit DelegateHandler class and access the received token, we then will be able to go validate it based on the different issuers.
This technique is also followed basically to hook in to the request response and compress the message , well that’s outside the discussion that we are having here.
Going back straight to the how we implement the message Handler especially with the introduction of OWIN middleware , it would be better for me to first summarize the steps before I include the code ( obviously without code this would be incomplete )
- Install the required Owin nugets (we also need Microsoft.Owin.Security.Jwt for Jwt token validation )
- Override SendAsunc() method, here is where our complete code of validation will reside.
- Switch the validation process based on the different issuers ( In the sample I have include token that is issued by ACS and AAD )
- Set the claim principal post validation.
- That’s it, we are good to go have a look at the code.
- One more thing we should remember is to register the custom Token handler to the webAPIconfig, this come be done simply by adding the following piece of code in the webAPIConfig
coming to the TokenVaidationHandler class, this is how it goes;
For extracting the tenant issuer information form the signing in token we can use the below code which parses the token against the MetadataAddress (for accessing the certificate) and sets the issuer and the signingTokens.
In order for us to read the signing Certs from the entityDesciptor from the above code we use the below method
The below code is basically to Build the response Message based on the HTTP statusCode.
Connecting the above Token Validator code we should be able to handle multiple token issuers in one Message handler. This might be of some use to those who are trying to handle multiple issuers . Please note that this is not a production ready code and the sole purpose of this is to depict how we can hook in Message handler for token validation. This would need further testing based on the varied scenario before its been used.