MvdD
MvdD

Reputation: 23436

How to get a token for downstream service in AAD

I have an MVC application in which I use OpenIdConnectAuthenticationMiddleware to authenticate the user against AAD. This MVC application uses a few backend services that require the user's authentication context.

If I register these services separately in AAD, I can get a token for them using AuthenticationContext.AcquireTokenSilentAsync. But registering these services separately with AAD seems wrong as they would require the user to consent to them separately (they are really part of the application).

So I'd like to use the JWT token I got from AAD when the user authenticated and use that as the bearer token for calling the downstream services. I realize that these services need to have the same audience as the MVC application.

But how do I get that JWT token. The ClaimPrincipal's first identity does not have a bootstrap context.

Upvotes: 3

Views: 3359

Answers (2)

vibronet
vibronet

Reputation: 7394

Please note that having your services admit tokens with the same audience opens you up to token forwarding attacks. I would not recommend that. Also, the consent should happen in a single page and with a single click - hence in terms of user impact there isn't really much difference. That said. If you are really set in it, you can enforce the presence of the token in the bootstrapcontext by switching to true the flag SaveSignInToken. See

app.UseOpenIdConnectAuthentication(
            new OpenIdConnectAuthenticationOptions
            {
                ClientId = clientId,
                Authority = authority,
                TokenValidationParameters = new System.IdentityModel.Tokens.TokenValidationParameters{SaveSigninToken=true},
                PostLogoutRedirectUri = postLogoutRedirectUri
            });

Upvotes: 7

dstrockis
dstrockis

Reputation: 1193

Edit The below is one way to achieve this, but it has some security implications. There is also a flag you can set for using the bootstrap context. Please see vibronet's answer for more.

In the OpenIdConnectAuthenticationOptions, if you configure a handler for the SecurityTokenValidated or AuthorizationCodeRecieved notifications, you can access the id_token in the notification's properties. You can then use that id_token as the bearer token in your service calls. There are several different ways you might make that id_token available in your controllers.

One caveat: the id_token will have the clientId of your web app as the aud claim, not the app id uri. So in your services, you should use the clientId guid as your audience.

Upvotes: 2

Related Questions