• Blazor
  • ASP.NET Core
  • .NET
  • C#
  • Wasm
  • WebAssembly

Blazor Wasm - Get Access Token for User

In this article I show, using ASP.NET Core Blazor Wasm, a quick snippet to get the AccessToken for a logged in User. Not much to it just using the IAccessTokenProvider, and if the user is signed in and they have are using an authentication type that provides an access token, like OpenID.

Checkout the Blazor Server - Get Access Token for User article with details on how this can be done for a Blazor Server Application!

Blazor - Getting Access Token from IAccessTokenProvider

Index.razor

@page "/"

<div>
    @AccessToken
</div>

Index.razor.cs


using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.WebAssembly.Authentication;

[Authorize]
public partial class Index : ComponentBase
{
    [Inject]
    IAccessTokenProvider TokenProvider { get; set; }

    public string AccessToken { get; set; }

    protected override async Task OnInitializedAsync()
    {
        var accessTokenResult = await TokenProvider.RequestAccessToken();
        AccessToken = string.Empty;

        if (accessTokenResult.TryGetToken(out var token))
        {
            AccessToken = token.Value;
        }
    }
}
Cody's logo image, it is an abstract of a black hole with a white Event Horizon.

Cody Merritt Anhorn

A Engineer with a passion for Platform Architecture and Tool Development.