Drdoomsalot
Drdoomsalot

Reputation: 362

How do I get the access token that was returned through Microsoft.AspNetCore.Components.Authorization

I am using Microsoft.AspNetCore.Components.Authorization to call my app registration and log in using my credentials. Everything works fine, but I can't figure out how to access my access token after logging in. I have an extremely simple app.

I followed the instructions here: Secure an ASP.NET Core Blazor WebAssembly standalone app with Azure Active Directory

I crteated the app and it looks pretty much exactly like the one on that page. However, I can't find any information on how to get the Token after logging in.

Thanks for any help.

Upvotes: 1

Views: 7575

Answers (2)

enet
enet

Reputation: 45596

To get the access token you need to inject IAccessTokenProvider and request the access token.

You may try the following, in a razor component...

@using Microsoft.AspNetCore.Components.WebAssembly.Authentication
@inject IAccessTokenProvider TokenProvider

var tokenResult = await TokenProvider.RequestAccessToken();

if (tokenResult.TryGetToken(out var token))
{
    ...
}

Upvotes: 4

Igal Flegmann
Igal Flegmann

Reputation: 642

If you are using the default application, the token gets added to the HTTP client when the requests are being sent to the back end. This is done in the program.cs where the http client is created:

   builder.Services.AddHttpClient("BlazorWasmWithAADAuth.ServerAPI", client => client.BaseAddress = new Uri(builder.HostEnvironment.BaseAddress))
        .AddHttpMessageHandler<BaseAddressAuthorizationMessageHandler>();

    // Supply HttpClient instances that include access tokens when making requests to the server project
    builder.Services.AddTransient(sp => sp.GetRequiredService<IHttpClientFactory>().CreateClient("BlazorWasmWithAADAuth.ServerAPI"));

if you are trying to get the token for calling another resource you will have to create another http client for that endpoint and add the token by creating a custom authorization message handler.

Upvotes: 1

Related Questions