0

How to get AD access token from login.microsoftonline.com and pass access token to web api controller? as I need "access token" as such to pass on to another partner company website url via post request.

Below code doing AAD authentication as expected but also I need "access token" as such,

public void ConfigureServices(IServiceCollection services)
    {
        services.Configure<CookiePolicyOptions>(options =>
        {
            // This lambda determines whether user consent for non-essential cookies is needed for a given request.
            options.CheckConsentNeeded = context => true;
            options.MinimumSameSitePolicy = SameSiteMode.None;
        });

        services.AddAuthentication(AzureADDefaults.AuthenticationScheme)
            .AddAzureAD(options => Configuration.Bind("AzureAd", options));

        services.Configure<OpenIdConnectOptions>(AzureADDefaults.OpenIdScheme, options =>
        {
            options.Authority = options.Authority + "/v2.0/";


            options.TokenValidationParameters.ValidateIssuer = false;
        });

        services.AddMvc(options =>
        {
            var policy = new AuthorizationPolicyBuilder()
                .RequireAuthenticatedUser()
                .Build();
            options.Filters.Add(new AuthorizeFilter(policy));
        })
        .SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
    }
191180rk
  • 735
  • 2
  • 12
  • 37
  • According to my understanding, you need the AD access token to call the API protected by AD then your API will call another application protected by AD. Is that right? Besides, could you please tell me your api application and partner company website are in the different tenant? – Jim Xu Mar 31 '20 at 02:34
  • Yes, my api application and partner company website are in the different tenant. My API will call another partner company application protected by inhouse-custom Authentication provider NOT AAD. Partner company application will verify the signature segment of AAD access token (provided by my app) to validate the authenticity of the token so that the token can be trusted by partner company app to proceed further. – 191180rk Mar 31 '20 at 04:27
  • Since you just use Azure AD to project your web API, I think you should validate token in api application. why do you use company application to validate token. – Jim Xu Mar 31 '20 at 05:51
  • Scenario is bit difficult to explain. Can we have chat? – 191180rk Mar 31 '20 at 05:59
  • Sorry. I cannot have chat. – Jim Xu Mar 31 '20 at 06:24
  • @JimXu, we as a vendor providing IAM service (like AAD) to our clients/partners which issues access token, which will be consumed by all our client/partners side applications. In order to issue access token, client app has to supply us password/clientcredentials/AADToken to prove its identity, if they supply AADToken then we need to validate the authenticity of the token so that the token can be trusted by our app to proceed further to issue access token & complete the call. The question is how to validate the authenticity of the AAD access tokens using c#? – 191180rk Mar 31 '20 at 09:14
  • If you want to know how to validate AAD token with C#, please refer to https://stackoverflow.com/questions/59840170/validating-the-token-recieved-from-azure-ad-b2c-using-the-values-from-jwks-uri/59851523#59851523 – Jim Xu Mar 31 '20 at 09:22
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/210647/discussion-between-191180rk-and-jim-xu). – 191180rk Mar 31 '20 at 09:30
  • Above code snippet attached in the original post, not exposing access token but internally it manage to get access token & validating, how to do it more transparent way? where I get access token & validate it using custom code for better understanding. – 191180rk Mar 31 '20 at 11:22
  • If you want to get Azure AD access token, you can use Microosft SDK `msal`. There are some [samples](https://learn.microsoft.com/en-us/azure/active-directory/develop/sample-v2-code) you can refer to – Jim Xu Apr 01 '20 at 01:10

2 Answers2

0

Above code snippet attached in the original post, not exposing access token but internally it manage to get access token & validating, how to do it more transparent way?

You can get tokens after authentication :

services.Configure<OpenIdConnectOptions>(AzureADDefaults.OpenIdScheme, options =>
{
    options.Authority = options.Authority + "/v2.0/";         // Microsoft identity platform
    options.SaveTokens = true;
    options.TokenValidationParameters.ValidateIssuer = false; // accept several tenants (here simplified)
});

And get tokes in controller :

var idToken = await HttpContext.GetTokenAsync("id_token"); 

But with your code snippets it won't return access token since you are implement the sign-in process , not token request . You shall use ADAL/MSAL to get access token for accessing the protected APIs . See code samples here .

where I get access token & validate it using custom code for better understanding.

You can understand the validation of token signature from here and here .

Nan Yu
  • 26,101
  • 9
  • 68
  • 148
  • Thanks for your understanding & solution. Now I can able to get token in controller/action which is decorated with [Authorize] & validated the token using AAD public keys, validation success which solves my problem. But your above statement "your code snippets it won't return access token since you are implement the sign-in process , not token request" which contradicts the real time behavior of my above code. Please clarify or let me if have missed anything to consider. – 191180rk Apr 01 '20 at 07:33
  • Your OIDC config which by default is OIDC sign in flow which grant type is id_token , you should use authorization code flow which grant type is code to get access token : https://learn.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-auth-code-flow – Nan Yu Apr 01 '20 at 08:03
  • [Authorize] attribute on top of controller, wont complain if id_token is supplied instead of access token? any c# sample to get access token via authorization code flow in transparent manner? any possibility to get access token after end user get authenticated via FIDO2 flow? – 191180rk Apr 01 '20 at 10:02
  • [Authorize] will check user's identity , that is related to id_token since claims from id_token will fill user's principle , HOw do you want to get the token ? check the code sample from above comment . – Nan Yu Apr 02 '20 at 01:23
  • How do you want to get the token? I want get token from AAD after FIDO authentication (or) after username&password verification. Also inside the controller I need a copy of that AAD access token for some business need. Thats it! the above provided code sample is not in user friendly manner. – 191180rk Apr 02 '20 at 05:43
  • Check code sample : https://github.com/Azure-Samples/active-directory-aspnetcore-webapp-openidconnect-v2/blob/master/4-WebApp-your-API/4-1-MyOrg/Client/Startup.cs#L57 . Use MSAL to get the token and save to cache which could be retired in controller . – Nan Yu Apr 02 '20 at 05:47
0

Hi please download and follow the instructions provided in the sample. It helps you set up a Web APi first and provides a client application that first signs in a user and then obtains an Access Token for a web Api

How to secure a Web API built with ASP.NET Core

Once you can get the sample to work, you can replace the sample's Web Api with your partner's Web Api.

Kalyan Krishna
  • 1,616
  • 15
  • 19