Authentication

💡 You can always refer to the sample project for additional guidance.

In order to implement User authentication with this library, you need to implement the IAuthenticationService in your Blazor Server project and specify it when calling the AddBlazorAuth method in your Blazor Server Program.cs file.

ℹī¸ IAuthenticationService will be available in both your Server and Client projects, but you should only implement it in your Server project. The Client project will use the Server implementation out-of-the-box by calling the Server's API.

Implementation

Sign-In Payload

Create a class for your Sign-In payload. This class will be used to pass the user's credentials to the IAuthenticationService implementation.

📜 This class needs to be serializable, so it can be passed between the Client and Server projects over http.

// Example Sign-In payload
public class SignInPayload
{
    public string Email { get; set; }
    public string Password { get; set; }
}

Sign-Up Payload

You don't need to do this if you don't want to implement the Sign-Up functionality.

Create a class for your Sign-Up payload. This class will be used to pass the user's credentials to the IAuthenticationService implementation.

📜 This class needs to be serializable, so it can be passed between the Client and Server projects over http.

// Example Sign-Up payload
public class SignUpPayload
{
    public string Email { get; set; }
    public string Password { get; set; }
}

Authentication Service

You can inherit from the base ServerSideAuthenticationService class in order to simplify the implementation of the IAuthenticationService in your Blazor Server project.

// Example Authentication Service
public class SampleServerSideAuthenticationService
    : ServerSideAuthenticationService<SignInPayload, SignUpPayload>
{
    protected override Task<AuthenticationResult> GetSignInResultAsync(SignInPayload signInPayload)
    {
        var jwtPair = CreateSampleJwtPair(); // Replace this with your actual authentication logic

        var authResult = AuthenticationResult.Success(jwtPair);

        return Task.FromResult(authResult);
    }

    protected override Task<AuthenticationResult> GetSignUpResultAsync(SignUpPayload signUpPayload)
    {
        var jwtPair = CreateSampleJwtPair(); // Replace this with your actual authentication logic

        var authResult = AuthenticationResult.Success(jwtPair);

        return Task.FromResult(authResult);
    }

    public override Task<AuthenticationResult> RefreshJwtPairAsync(string refreshToken)
    {
        var jwtPair = CreateSampleJwtPair(); // Replace this with your actual authentication logic

        var authResult = AuthenticationResult.Success(jwtPair);

        return Task.FromResult(authResult);
    }

    private JwtPair CreateSampleJwtPair()
    {
        return new JwtPair
        {
            AccessToken = "my-access-token",
            RefreshToken = "my-refresh-token"
        };
    }
}

Register the Authentication Service

Specify your IAuthenticationService implementation when calling the AddBlazorAuth method in your Blazor Server Program.cs file.

// Program.cs
builder.AddBlazorAuth<SampleServerSideAuthenticationService>();

Add the authentication endpoints in your Blazor Server Program.cs. This is required in order to allow the Client project to call the Server's API and use the server-side IAuthenticationService implementation.

// Program.cs
app.MapAuthEndpoints();

User Service

You can now use the IUserService in your Blazor Pages to Sign-In, Sign-Up, and Refresh the JWT Pair. The IUserService will call your IAuthenticationService implementation to perform these actions. Upon receiving a response, the IUserService will then update the User's state. For additional guidance, see sample flows in Use Cases section.

ℹī¸ You can also inject and use the IAuthenticationService directly in your Blazor application, it will process the Sign-In, Sign-Up, and Refresh Token requests without updating the User's state. You can inject the IAuthenticationService in the wasm part of your app. It will call the Server's WebAPI to perform the authentication action and return the same response as if the action was performed on the server. Keep in mind that in this case a serialization/deserialization process will take place in order to pass the data between the Client and Server projects.

Token duration

You can specify the duration of your access token and refresh token whenever you are providing your JwtPair to Blazor.Auth. The duration of the access token should normally be short, while the refresh token should normally be long-lived.

return new JwtPair
    {
        AccessToken = "my-access-token"
        RefreshToken = "my-refresh-token"
        AccessTokenExpiresAt = DateTimeOffset.UtcNow.AddMinutes(15),
        RefreshTokenExpiresAt = DateTimeOffset.UtcNow.AddDays(7)
    }

⚠ī¸ Not providing an expiration date for the tokens will result in them being session-scoped. This means that the tokens will expire when the browser tab closes.

Sign out

You can sign the user out by calling the SignOutAsync method of the IUserService. This will clear the user's JwtPair.

await UserService.SignOutAsync();
NavigationManager.NavigateTo("/", true);