Implementing User Authentication in Blazor Apps

The topic for this blog came up in developing Blazor Picture Gallery.

Blazor Picture Gallery permits an anonymous user to rate a picture but only an authenticated user can upload a picture to Blazor Picture Gallery.

Blazor Picture Gallery was developed as a Blazor Web App using MudBlazor components. It runs on Azure with an Azure SQL Database and Azure Storage for the images.

I chose to use Server-side authentication. This meant that when I created the Web App, I specified Server as the Interactive render mode and Individual Accounts as the Authentication type.

This generates a template for Identity. The server handles all authentication requests, and the Identity components render statically on the server.

The template will add an ApplicationDbContext which uses SQL Server. It also includes the addition of Identity in Program.cs.

builder.Services.AddIdentityCore<ApplicationUser>(options => options.SignIn.RequireConfirmedAccount = false)
    .AddEntityFrameworkStores<ApplicationDbContext>()
    .AddSignInManager()
    .AddDefaultTokenProviders();

When I tried to access the template components, they flickered. This is because of how they render on the server. To handle, this, I added code to set the render mode in App.razor.

<html lang="en">
...
<body>
<Routes @rendermode="@RenderModeForPage" />
...
</body>
<html>
@code {
    [CascadingParameter]
    private HttpContext HttpContext { get; set; } = default!;

    private IComponentRenderMode? RenderModeForPage => HttpContext.Request.Path.StartsWithSegments("/Account")
        ? null
        : InteractiveServer;
}
Login page for a web application featuring fields for email and password, a 'Log in' button, and a Google login option.

I also chose to add Google authentication.

The requirement for this picture gallery is that only an authenticated user can upload pictures.

Screenshot of Blazor Picture Gallery user interface displaying an upload button, user rating options for images, and a user email address.

I created an UploadComponent that was only visible to an authenticated user. I used an AuthorizeView.

<AuthorizeView>
    <Authorized><UploadComponent OnUploaded="Uploaded"></UploadComponent></Authorized>
    <NotAuthorized>
        To upload, <NavLink href="Account/Register">
            Register
        </NavLink> or 
        <NavLink href="Account/Login">Login</NavLink>
    </NotAuthorized>
</AuthorizeView>

To add the Google authentication, I followed Easily Implement Google Authentication

To summarize, one must first create a Google client and integrate its credentials into appsettings.json. Then it is necessary to run

Install-Package Microsoft.AspNetCore.Authentication.Google

Both the Identity provider and the Google provider have to be added in Program.cs.

builder.Services.AddAuthentication(options =>
    {
        options.DefaultScheme = IdentityConstants.ApplicationScheme;
        options.DefaultSignInScheme = IdentityConstants.ExternalScheme;
    })
    
    .AddIdentityCookies();

builder.Services.AddAuthentication().AddGoogle(o =>
{
    o.ClientId = builder.Configuration.GetValue<string>("Authentication:Google:ClientId");
    o.ClientSecret = builder.Configuration.GetValue<string>("Authentication:Google:ClientSecret");
    o.ClaimActions.MapJsonKey("urn:google:com","link");
    o.ClaimActions.MapJsonKey("urn:google:profile", "image");
});

Then a user can use the Login page to login with Google.

This results in a picture gallery with images rendered by a MudImage in a MudLayout. An Upload component is only visible to a logged in user. The user may authenticate with either the built-in Identity or with Google.



Discover more from Schroeder Consulting LLC

Subscribe to get the latest posts sent to your email.

Carolyn Schroeder, Sole Proprietor and IT Consultant

Carolyn worked in a number of Kansas City area corporate environments before establishing her own consulting business. She is dedicated to architecting the best possible solutions to meet the needs of her clients. She is passionate about learning the cutting edge tools necessary to drive business forward.

Let’s connect