Authentication

Introduction

Most web applications require some form of authentication. Spark provides this out of the box by using .NET’s authentication with it’s own custom cookie provider.

Spark also builds the login, logout, register and profile edit pages for you. Feel free to customize their look and feel how you see fit.

Configuration

Authentication settings can be configured in your appsettings.json file.

{
    "Spark": {
        "Auth": {
            "LoginPath": "/login",
            "LogoutPath": "/logout",
            "AccessDeniedPath": "/access-denied",
            "CookieExpirationDays": 5,
        },
    }
}

Setup

Spark’s authentication is setup for you in AppServiceRegistration.AddAppServices().

services.AddAuthentication<IAuthValidator>(config);

The implementation for IAuthValidator is the Application.Services.Auth.AuthValidator.cs class. This service comes with 1 method that is called behind the scenes whenever an authentication check needs to occur, ValidateAsync().

User Data

The User Model

Every Spark app comes with a User.cs class in the Application/Models directory. This acts as your schema for your users table and also the class that is used during authentication.

public class User : BaseModel
{
    public User()
    {
        UserRoles = new HashSet<UserRole>();
    }

    public int Id { get; set; }

    public string Name { get; set; }

    public string Email { get; set; }

    public string Password { get; set; }

    public string? RememberToken { get; set; }

    public DateTime? EmailVerifiedAt { get; set; }

    public virtual ICollection<UserRole> UserRoles { get; set; }
}

Users also have Roles tied to them for authorization. You can read more about that on the Authorization page.

Accessing User Data

Spark comes with out of the box methods to make it easy to query the authenticated User’s model.

The Application/Services/Auth/AuthService.cs class comes with a GetAuthenticatedUser() method. This will return the User model if the person logged in or null otherwise.

The AuthService can be dependency injected in your services or Razor components.

@page "/"
@inject AuthService AuthService

...

Protecting Routes & Pages

If you have routes in your app you only want logged in users to see, use the Authorize attribute.

@page "/dashboard"
@attribute [Authorize]
<section class="max-w-5xl mx-auto py-28 min-h-screen px-4">
    <article>
        <h1 class="text-2xl font-bold text-gray-800">
            User Dashboard
        </h1>
    </article>
</section>

Protecting Page Content

Sometimes you need more granular control when protecting a route or page.

For instance, lets say you want to show a page regardless if the user is authenticated or not. But you want to show the login button if they aren’t authenticated. Likewise, you want to show the logout button if they are authenticated.

In Blazor you can accomplish this by using the <AuthorizeView> tag helper.

<nav>
    <AuthorizeView>
        <Authorized>
            <a href="/logout">Logout</a>
        </Authorized>
        <NotAuthorized>
            <a href="/login">Login</a>
        </NotAuthorized>
    </AuthorizeView>
</nav>

Stay up to date with Spark on Twitter or our Newsletter

Looking for .NET jobs? Check out Dotnet Jobs for weekly job postings.