What is Blazor? A Tutorial on Building Web Apps with Authentication

Just two notes from when I was adding these helpful code bits to my project that may help others:

  • If you’re just going to connect from the wasm to the host, extend BaseAddressAuthorizationMessageHandler instead of AuthorizationMessageHandler. It sets the URL for you so you don’t need the ConfigureHandler() call.

  • You need to put your MessageHandler into the services, e.g.

          builder.Services.AddScoped<Auth0MessageHandler>();
    
          builder.Services.AddHttpClient("ServerAPI", client => 
              client.BaseAddress = new Uri(builder.HostEnvironment.BaseAddress))
                  .AddHttpMessageHandler<Auth0MessageHandler>();
    
2 Likes

Thanks for sharing that @zgrose!

Thanks for your contribution @zgrose!

Is it possible to redirect a user to the register page directly instead of going to the login first and then navigate to the register?

Hey @nathanuel81,
you should be able to get this by customizing the Universal Login page.
Basically, you should access the Universal Login section in your Auth0 Dashboard and modify the page’s code in the Login tab.

Check out this document to have an idea of the overall process.

For your specific needs, you should work on the initialScreen option of the Configuration object.

Hey Andrea,

I was more thinking along the lines of having a button to go register and another to login within my UI which would redirect the user to the relevant page of the universal login.

I done something similar in an MVC application using the following code:

    [AllowAnonymous]
    public async Task SignUp(string returnUrl = "/")
    {
        var properties = new AuthenticationProperties { RedirectUri = returnUrl };
        properties.Items.Add("screen_hint", "signup");
        await HttpContext.ChallengeAsync("Auth0", properties);
    }

Is there a way to pass this screen_hint property in Blazor?

Hey @nathanuel81,
I didn’t try, but I think you can do it by handling the OnRedirectToIdentityProvider event (see here), similarly to how you are handling the logout redirection.
Let me know if it works.

I’ve successfully added Auth0 authentication to my existing Blazor Server application.
Authentication (login/logout/…) & views are authorized properly. But how could I protect the back-end controllers which are also part of the application?
Could I easily get the token from the razor pages and pass it through the controller ?
f.e. via httpclient

That’s what the message handler is doing for you. Appending the Bearer token into the headers. Then you just need to put the JWT bearer bits in the server.

1 Like

Thanks for sharing that with the rest of community @zgrose!

Thank you for your response.

In which package is “Auth0MessageHandler” defined? I don’t seem to find this directly on Github

In this thread, the post by nathanuel81.
The official docs link is: ASP.NET Core Blazor WebAssembly additional security scenarios | Microsoft Learn

The version I created based on nathanuel81’s addition uses a different constructor otherwise it’s basically the same thing.

-z

public class Auth0MessageHandler : BaseAddressAuthorizationMessageHandler
{
    private readonly IAccessTokenProvider _provider;

    public Auth0MessageHandler(IAccessTokenProvider provider,
        NavigationManager navigationManager)
        : base(provider, navigationManager)
    {
        _provider = provider;
    }

    protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        var accessTokenResult = await _provider.RequestAccessToken();

        if (accessTokenResult.TryGetToken(out var token))
        {
            if (!string.IsNullOrWhiteSpace(token.Value))
                request.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token.Value);
            else
                throw new HttpRequestException("No Token!!");
        }

        return await base.SendAsync(request, cancellationToken);
    }
}

Thank you. I’ve created this handler however, I receive the following error

.Auth0MessageHandler’: Unable to resolve service for type ‘Microsoft.AspNetCore.Components.WebAssembly.Authentication.IAccessTokenProvider’ while attempting to activate

Shouldn’t this Interface be resolved by the framework itself? Do I need to manually resolve this?
Creating a Blazor Server app & using Typed HttpClient

        services.AddScoped<Auth0MessageHandler>();

        services.AddHttpClient<ApiService>(client =>
        {
            client.BaseAddress = new Uri("https://localhost:44364/");
        }).AddHttpMessageHandler<Auth0MessageHandler>();

Did you add OIDC to the services? I believe that extension is what adds the token provider.
Something along the lines of:

            builder.Services.AddOidcAuthentication(options =>
        {
            builder.Configuration.Bind("Auth0", options.ProviderOptions);
            options.ProviderOptions.ResponseType = OpenIdConnectResponseType.Code;
        });
1 Like

Let us know @jens.bruggeman if what @zgrose suggested solved your hurdle!

Hi,

Firstly, sorry if this a rookie question, I’ve never had to deal with authentication before.

I’m creating a Blazor Server Side application, and implemented Auth0 using the following blog post by Auth0:

I’ve created a user and added a property in the App_Metadata, to let me set information for the user but stuff they can’t change (CompanyId: 3).

How do I get the CompanyId from the App_Metadata in Auth0 into my application? It’s not a role, but gives me information about the user to link them to more data in my own database.

Hey there @dan6!

Migrating your post here as this is the thread for issues and questions regarding this blog article.

1 Like

Hi @dan6,
Welcome to Auth0 Community and thanks for reading this blog post.

Regarding your question, in general, you should find your user’s data in the User.Identity object. However, there are two points to point out:

  1. By default, the User.Identity object is not automatically populated. You should apply a few changes to your code in order to map user’s data to that object. Please, take a look at this to get more info.

  2. The user’s data that populate the User.Identity object comes from the ID token issued by Auth0. However, these data are just the standard OIDC claims.
    To include additional information as part of the ID token (the App_Metadata, for example), you need to add custom claims through a rule.
    Please, check out these documents to learn more:

2 Likes

Can we please get a working example for Blazor .Net 5, Asp.Net Core Hosted WASM. This example does not work. A sample project would be appreciated.

Hi @ehilimire,
Welcome to the Auth0 Community!
An update to this article is under consideration. I will announce it here when it becomes available (hopefully very soon).
Thank you for your interest :pray:

2 Likes