Authentication in server-side Blazor applications

Preview 6 version of ASP.NET Core 3.0 is released and one interesting new feature is authentication and authorization for server-side Blazor applications. This blog post goes through work currently done and shows how authentication works with server-side Blazor applications.

Creating server-side Blazor application

When creating new server-side Blazor application there’s active change link in Authentication section. Clicking on this link opens authentication options dialog.

Adding authentication to server-side Blazor application

There’s same change link also for other types of Blazor applications but currently it is greyd out.

When Blazor application is created we can see some interesting things in Blazor project.

Server-side Blazor application with authentication opened in Visual Studio

Things to notice:

  • Server-size Blazor uses ASP.NET Core Identity (without scaffolding).
  • For local user accounts Entity Framework Core database context and migrations are created.
  • There’s new LoginDisplay Razor view in project.

Registering authentication

With ASP.NET Core Identity things are actually straightforward and there’s no reason to discuss it. It’s more interesting to find out how things are configured in Startup class.

public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddDbContext<ApplicationDbContext>(options =>
            options.UseSqlServer(
                Configuration.GetConnectionString("DefaultConnection")));
        services.AddDefaultIdentity<IdentityUser>()
            .AddEntityFrameworkStores<ApplicationDbContext>();
        services.AddRazorPages();
        services.AddServerSideBlazor();
        services.AddSingleton<WeatherForecastService>();
    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
            app.UseDatabaseErrorPage();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
            app.UseHsts();
        }

        app.UseHttpsRedirection();
        app.UseStaticFiles();

        app.UseRouting();

        app.UseAuthentication();
        app.UseAuthorization();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
            endpoints.MapBlazorHub();
            endpoints.MapFallbackToPage("/_Host");
        });
    }
}

From ConfigureServices() and Configure() methods we can see that there’s nothing special or new. It’s all same as with ASP.NET Core Identity and regular ASP.NET Core applications. It makes sense as server-side Blazor application runs also user interface events in server using SignalR for data communication.

AuthorizeView component

Let’s take a look inside LoginDisplay Razor view.

<AuthorizeView>
    <Authorized>
        <a href="Identity/Account/Manage">Hello, @context.User.Identity.Name!</a>
        <a href="Identity/Account/LogOut">Log out</a>
    </Authorized>
    <NotAuthorized>
        <a href="Identity/Account/Register">Register</a>
        <a href="Identity/Account/Login">Log in</a>
    </NotAuthorized>
</AuthorizeView>

The markup probably doesn’t need any comments. Okay, I would like to say that it is really clean and communicative. No clutter, no ugly mess of markup – just nice and clean.

When sniffing around in Blazor libraries we can see that AuthorizeView is new Blazor component that comes with ASP.NET Core components library. In LoginDisplay view it has only basic use – just show different piece of HTML to authenticated and anonymous users.

Actually we can use Authorize view also on other pages to show sidebar blocks or header and footer content based on if user is authenticated or not. I think component like this will be very useful in Blazor applications to avoid ugly checks for authenticated user in Blazor views.

For client-side Blazor applications it’s possible to use custom authentication. My blog post Azure AD authentication in Blazor using ADAL.js shows how to use Azure AD authentication with client-side Blazor applications.

Blazor authentication in action

Let’s take a look at some screenshots illustrating Blazor authentication. Before running application make sure you build application and run Update-Database command from package manager console.

This is default page of server-side Blazor application when authentication is enabled.

Default page of server-side Blazor application

Mostly it looks like default page before but notice Register and Log in links on top bar. Registration page is known for us from ASP.NET Core applications.

Default registration page of server-side Blazor application

After successful registration we are redirected back to front page and here is how it looks for authenticated user.

User is authenticated to server-side Blazor application

Wrapping up

Support for authentication is welcome to Blazor applications and with server-side Blazor applications the first step is made. It’s good to see that authentication options known from regular ASP.NET Core applications are used also here. Also I think AuthorizeView component is great approach to display content based on if user is authenticated or not. Now let’s wait for next releases of Blazor and see how client-side Blazor applications get also out-of-box support for authentication.

Liked this post? Empower your friends by sharing it!

Gunnar Peipman

Gunnar Peipman is ASP.NET, Azure and SharePoint fan, Estonian Microsoft user group leader, blogger, conference speaker, teacher, and tech maniac. Since 2008 he is Microsoft MVP specialized on ASP.NET.

    6 thoughts on “Authentication in server-side Blazor applications

    • June 18, 2019 at 5:53 pm
      Permalink

      Nice blog. Is there a way to override the authentication scaffolding? I tried but could not get it to work.

    • June 24, 2019 at 6:01 pm
      Permalink

      Nice…
      How to consume existing users database for authentication which is not based on Identity framework.
      Secondly how to customize existing login for Active Directory Authentication.

    • July 7, 2019 at 9:37 am
      Permalink

      With server-side Blazor you can build your own login page and use whatever login method you like. The page can be regular Razor view that manages authentication. Same goes for Azure AD.

    • August 8, 2019 at 6:23 pm
      Permalink

      Well, that’s all well and good but there’s no local cshtml pages to modify in the Identity area. Spin up a new scaffold like in Core 2.x to create the pages locally and you get:
      The type or namespace name ‘IHostingEnvironment’ could not be found (are you missing a using directive or an assembly reference?)

      This is a time eater!

      Love Blazor but might want to look into this.

      Thanks all

    • August 8, 2019 at 8:29 pm
      Permalink

      Blazor and related tooling is still in preview and I wouldn’t be surprised if this is not the only issue.

      Anyway we don’t have to wait long as .NET Core 3.0 will be announced during .NET Conf 2019 (https://www.dotnetconf.net/ free online seminar). So, next month we will get first stable release of .NET Core 3.0, ASP.NET Core 3.0 and server-side Blazor.

    • October 17, 2019 at 4:30 am
      Permalink

      Hi,

      Hope you are doing well. Would you please guide me how to authenticate user with asp.net core identity using custom login page (razor)?

      I shall be very thanks full to you.

      Regards

    Leave a Reply

    Your email address will not be published. Required fields are marked *