Attaching the Bearer Token to Claims Identity in ASP.NET Core to implement On-Behalf-Of Flow

When you setup an ASP.NET Core web API project and go through the wizard to associate it with an Azure Active Directory tenant it will add the necessary plumbing within your project to get it all working. However, if you are ever in a place where you need to use on-behalf-of flow to obtain another token maybe for a different service like Azure Active Directory you’ll need access to the bearer token that you receive from the client.

You can get quick access to the bearer token by modifying your JwtBearerOptions. By default when you go through the standard wizard and setup Azure Active Directory authentication it will only contain two lines of code setting the Audience and the Authority. You need to modify it to handle the OnTokenValidated Event:

This will essentially attach the bearer token (i.e. access token) as a claim. This will allow you to pull it back from within your Controllers like this:

Notice how I’m using the standard quick access shortcut of “User.Identity” to access the claim. I’m also using the magic string I specified in the OnTokenValidated event to look up my access token. Once I get it, I can attach the token to future web API requests to other Web APIs to request access on behalf of the user.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s