3
votes

I followed the sample code here to create a MVC web app with Azure AD multi-tenant OpenID authentication. I use the following code to get user sign in.

public void SignIn()
{
    if (!Request.IsAuthenticated)
    {
        HttpContext.GetOwinContext().Authentication.Challenge(new AuthenticationProperties { RedirectUri = "/" }, OpenIdConnectAuthenticationDefaults.AuthenticationType);
    }
}

Now I need to send a web api call which is protected by my Azure AD as well. Currently, before I send the request I use ADAL library to ask users to login again and get the access token like this.

AuthenticationContext ac = new AuthenticationContext(authority);
AuthenticationResult ar = ac.AcquireToken(resourceID, clientID, redirectURI, PromptBehavior.Always); 
string accessToken = ar.AccessToken;

However, since the authentication used in the MVC(if the user is from my AD) is the same as the one used to protect the web api. I'm wondering if there is a way to get the access token when user login with this openID authentication so that I can skip the second login with ADAL?

UPDATE: Following vibronet's answer, I am trying to use the following code to get the token:

string authority = "https://login.windows.net/ucdavisprojecthotmail.onmicrosoft.com";

ClientCredential clientcred = new ClientCredential(clientId, appKey);
AuthenticationContext authContext = new AuthenticationContext(authority);
AuthenticationResult result = authContext.AcquireTokenSilent(resourceID, clientcred, new UserIdentifier(userObjectID, UserIdentifierType.UniqueId));

Here, this code is used in an MVC web app and the clienId and appKey is the clientID and key of the web API I want to call. The resoureID is the APP ID URI of the web API obtained in Azure portal.

However, I got this error: Failed to acquire token silently. Call method AcquireToken. Anything I was missing?

1

1 Answers

2
votes

Absolutely. Check out https://github.com/AzureADSamples/WebApp-WebAPI-MultiTenant-OpenIdConnect-DotNet, it's like the sample you've been working with but with in addition the access token acquisition and use you are asking about. Also note, AcquireTokenSilent can only work if you have a token in the cache - to be used directly or refreshed. FInally: when you ask for a token, you must specify both the ID fo the resource you want a token for, and the clientID of the application doing the request. In your code, you appear to have used the clientID of the target app. Please refer to the sample I linked above, it shows the exact pattern to be used in this scenario.