s

asp net core 5.0 how to get access token of user authenticated using active directory edit button Edit

author
Murugan Andezuthu Dharmaratnam | calendar 13 August 2021 | 1570

In this article we will look at how to read the JWT token. I have an asp .net core 5.0 mvc application where the user gets authenticated using AD ( active directory ), and I wanted to get the JWT token to send it to another application. Here I am assuming that you have already written an application where user is authenticated using AD and you are unable to get the JWT token.

ref: https://docs.microsoft.com/en-us/azure/active-directory/develop/scenario-web-app-call-api-acquire-token?tabs=aspnetcore

Solution

Inject to the HomeController Constructor & the code to get access token in action method Index

        readonly ITokenAcquisition tokenAcquisition;
        public HomeController(ILogger logger, ITokenAcquisition tokenAcquisition)
        {
            _logger = logger;
            this.tokenAcquisition = tokenAcquisition;
        }

        public IActionResult Index()
        {
            // Acquire the access token.
            string[] scopes = new string[] { "user.read" };
            string accessToken = tokenAcquisition.GetAccessTokenForUserAsync(scopes).Result;

            return View();
        }

in startup.cs make the following changes

ConfigureServices method

            services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
                .AddMicrosoftIdentityWebApp(Configuration.GetSection("AzureAd"))
                .EnableTokenAcquisitionToCallDownstreamApi(new string[] { "user.read" })
                .AddInMemoryTokenCaches();

do not forget to add ClientSecret in appsettings.json file.

  "AzureAd": {
    "Instance": "https://login.microsoftonline.com/",
    "Domain": "yourdomain.com",
    "TenantId": "8e5da8dc-f3fb-4c5f-985a-***********",
    "ClientId": "f6f5ab30-547b-409d-**********",
    "CallbackPath": "/signin-oidc",
    "ClientSecret": "VPz-46UGN.~K24E70.o0KfoZq9X******"
  },