Authentication
- Introduction
- Complete Example: Generated Login Flow
- Authentication Quickstart
- Manually Authenticating Users
- Logging Out
- Password Confirmation
- More Authentication Features
Introduction
DotBlaze's authentication is modelled on Laravel's session guard and Breeze, integrated with ASP.NET Core authentication using the Session scheme. It does not use ASP.NET Core Identity. The framework provides the Auth facade, the auth, guest, and verified middleware, "remember me" tokens, the Password broker, and password hashing; the controllers and views are your own code. Run dotblaze make:auth to add a complete, tested implementation to your application: it copies the sample blog's login, registration, password reset, and email verification controllers, requests, views, and routes/auth.cs, and registers the routes in RouteServiceProvider (see console).
Related pages: Authorization (Gate and policies), Resetting Passwords, Email Verification, and Rate Limiting (login throttling).
Configuration
Authentication is configured in config/Auth.cs:
public class AuthConfig : ConfigFile
{
public override object Values() => new
{
home = "/",
login = "/login",
remember_days = 400,
passwords = new { expire = 60, throttle = 60 },
verification = new { expire = 60 },
};
}| Key | Default | Description |
|---|---|---|
home | / | Where the guest middleware sends users who are already logged in. |
login | /login | Where the auth middleware sends guests. |
remember_days | 400 | How long the "remember me" cookie lasts. |
passwords.expire, passwords.throttle | 60, 60 | Reset token lifetime (minutes) and the wait between reset emails (seconds). See passwords. |
verification.expire | 60 | Lifetime of email verification links in minutes. |
password_timeout | 10800 | Seconds a password confirmation lasts. |
model | (auto) | Full type name of the user model, only needed if several types implement IAuthenticatable. |
Login uses the session driver in config/Session.cs: memory, redis, database, or cookie. The session cookie defaults to .dotblaze.session; the "remember me" cookie is .dotblaze.remember. session.lifetime controls the sliding lifetime of both session data and login. There is no separate .dotblaze.auth ticket. See session upgrading notes when migrating an existing app.
The User Model
Any model that implements IAuthenticatable can log in. By default DotBlaze uses its Id and Password properties:
namespace DotBlazeApp.Models;
public class User : Model<User>, IAuthenticatable, INotifiable, ICanResetPassword, IMustVerifyEmail
{
public long Id { get; set; }
[Fillable] public string Name { get; set; } = "";
[Fillable] public string Email { get; set; } = "";
public DateTime? EmailVerifiedAt { get; set; }
[Fillable, Hidden, Cast(typeof(Hashed))] public string Password { get; set; } = "";
[Hidden] public string? RememberToken { get; set; }
public DateTime? CreatedAt { get; set; }
public DateTime? UpdatedAt { get; set; }
}RememberToken (the remember_token column, t.RememberToken() in a migration) is needed for "remember me". INotifiable, ICanResetPassword, and IMustVerifyEmail are for notifications, password reset, and email verification; leave out the ones you do not use.
The Hashed cast hashes the password when the model is saved (an already hashed value is left alone), and [Hidden] keeps it out of JSON. If your properties are named differently, implement the interface's methods yourself:
public class Member : Model<Member>, IAuthenticatable
{
public long MemberId { get; set; }
public string PasswordHash { get; set; } = "";
public object GetAuthIdentifier() => MemberId;
public string GetAuthPassword() => PasswordHash;
}DotBlaze finds the user type automatically when exactly one type in your application implements IAuthenticatable. With more than one, set model in config/Auth.cs to the full type name (for example model = "DotBlazeApp.Models.User").
Authentication Quickstart
Routes
Route.Middleware("guest").Group(() =>
{
Route.Get<AuthController>("/login", c => c.ShowLogin).Name("login");
Route.Post<AuthController>("/login", c => c.Login);
Route.Get<AuthController>("/register", c => c.ShowRegister).Name("register");
Route.Post<AuthController>("/register", c => c.Register);
});
Route.Middleware("auth").Group(() =>
{
Route.Post<AuthController>("/logout", c => c.Logout).Name("logout");
});
Route.Middleware("auth", "verified").Group(() =>
{
Route.Resource<PostController>("/posts", parameter: "post");
});routes/auth.cs from make:auth also has the password reset and verification routes.
Registering Users
using Microsoft.AspNetCore.Mvc;
using SampleApp.Models;
using SampleApp.Requests;
namespace SampleApp.Controllers;
public class AuthController : BaseController
{
// Where users go after logging in or registering.
const string Home = "/posts";
// Failed logins allowed per email and IP address before the form is locked for a minute.
const int MaxAttempts = 5;
public IActionResult ShowLogin() => View("Login");
public async Task<IActionResult> Login(LoginRequest request)
{
var key = $"login:{request.Email.ToLowerInvariant()}|{HttpContext.Connection.RemoteIpAddress}";
if (await RateLimiter.TooManyAttempts(key, MaxAttempts))
{
var seconds = await RateLimiter.AvailableIn(key);
return Back().WithErrors(new { Email = $"Too many login attempts. Please try again in {seconds} seconds." }).WithInput();
}
var user = await Auth.Validate(new { request.Email, request.Password });
if (user is null)
{
await RateLimiter.Hit(key);
return Back().WithErrors(new { Email = "These credentials do not match our records." }).WithInput();
}
await RateLimiter.Clear(key);
if (user is ITwoFactorAuthenticatable twoFactor && TwoFactor.Enabled(twoFactor))
{
await TwoFactor.Challenge(twoFactor, request.Remember);
return RedirectRoute("two-factor.login");
}
await Auth.Login(user, request.Remember);
return Intended(Home);
}
public IActionResult ShowRegister() => View("Register");
public async Task<IActionResult> Register(RegisterRequest request)
{
var user = await Models.User.Create(new { request.Name, request.Email, request.Password });
await user.SendEmailVerificationNotification();
await Auth.Login(user);
return RedirectTo(Home);
}
public async Task<IActionResult> Logout()
{
await Auth.Logout();
return RedirectTo("/");
}
}Registration sends the verification email; failed logins are throttled.
LoginRequest and RegisterRequest are form requests. The login form posts Email, Password, and a Remember checkbox:
<form method="post" action="@Route("login")">
@Csrf()
<input type="email" name="Email" value="@Old("Email")" />
@if (Error("Email") is string error) { <span>@error</span> }
<input type="password" name="Password" />
<label><input type="checkbox" name="Remember" value="true" /> Remember me</label>
<button type="submit">Log in</button>
</form>NOTE
Inside the SampleApp.Controllers namespace, User refers to the controller's User property (the ClaimsPrincipal), so the model is written as Models.User.
Retrieving the Authenticated User
if (Auth.Check()) { /* logged in */ }
if (Auth.Guest()) { /* not logged in */ }
var user = Auth.User<User>(); // the User model, or null
var id = Auth.Id(); // the identifier as object, or nullThe user is loaded from the database once per request, so Auth.User<User>() returns current data. If the user's row has been deleted, the cookie is cleared and the request continues as a guest. The facade works in controllers, views, middleware, and form requests:
@if (Auth.Check())
{
<span>@(Auth.User<User>()!.Name)</span>
}Protecting Routes
Attach the auth middleware to routes that need a logged-in user, and guest to pages only guests should see. Guests hitting an auth route are redirected to login; JSON requests get 401. See middleware.
Redirecting to the Intended URL
When the auth middleware redirects a GET request, it remembers the URL. After a successful login, Intended(fallback) redirects there, or to the fallback when nothing was remembered:
return Intended("/posts");Manually Authenticating Users
Auth.Attempt takes the credentials as an anonymous object (or dictionary). The Password entry is checked against the stored hash; every other entry must equal the matching model property:
if (await Auth.Attempt(new { request.Email, request.Password }))
{
return Intended("/posts");
}Extra conditions are just more properties: new { request.Email, request.Password, Active = true } only logs in active users (assuming the model has an Active property). It returns true and logs the user in when the credentials match, false otherwise. Credentials without a Password, or with a name that is not a model property, throw an ArgumentException.
When no user matches, DotBlaze still checks the password against a dummy hash, so the response time does not reveal whether an email address is registered.
Remembering Users
Pass true as the second argument to keep the user logged in after the browser closes:
await Auth.Attempt(new { request.Email, request.Password }, remember: true);Like Laravel, the login cookie itself still ends with the browser session (or after lifetime minutes of inactivity). "Remember me" adds a second, encrypted .dotblaze.remember cookie that lasts remember_days and holds the user id, a random token stored in the remember_token column, and a fingerprint of the password hash. When a request arrives without a valid login cookie, DotBlaze logs the user in again from it. The cookie stops working when:
- the user logs out (a new token is saved, which logs out every remembered device), or
- the password changes (the fingerprint no longer matches).
A user model without a RememberToken property throws when remember is true.
Login tickets also contain a fingerprint of the password hash. Each HTTP request checks it against the current user: changing or resetting the password invalidates existing login tickets and clears their session on the next request. Tickets issued before this protection was added are rejected too; plan for users to sign in again after upgrading. This does not revoke personal API tokens or disconnect already-open WebSocket connections.
Logging In a User Instance
To log in a user you already have, for example right after registration:
await Auth.Login(user);
await Auth.Login(user, remember: true);Logging Out
public async Task<IActionResult> Logout()
{
await Auth.Logout();
return RedirectTo("/");
}Logging out also deletes the "remember me" cookie, replaces the user's remember token, and clears the session (logging in gives the session a new id). Log out from a POST route with a CSRF-protected form, never from a link:
<form method="post" action="@Route("logout")">
@Csrf()
<button type="submit">Log out</button>
</form>Password Confirmation
Some pages should ask for the password again, even from a logged-in user: account deletion, changing an email address, billing. Put the password.confirm middleware on them (after auth). A user who has not confirmed their password in the last three hours (auth.password_timeout) is sent to the password.confirm route, and back afterwards; JSON requests get 423 Locked. From the sample app:
Route.Get<AccountController>("/settings", c => c.Show).Name("settings").Middleware("password.confirm");
Route.Delete<AccountController>("/settings/account", c => c.Destroy).Name("account.destroy").Middleware("password.confirm");dotblaze make:auth adds the confirmation screen (ConfirmablePasswordController and auth/ConfirmPassword.blade.html) and its routes. The controller checks the password with Auth.ValidatePassword and records the confirmation in the session with Auth.PasswordConfirmed():
public async Task<IActionResult> Store([FromForm] string? password)
{
if (string.IsNullOrEmpty(password) || !Auth.ValidatePassword(password))
return Back().WithErrors(new { Password = "The provided password is incorrect." });
await Auth.PasswordConfirmed();
return Intended("/");
}To send users to another route, name it: password.confirm:account.confirm.
More Authentication Features
- API tokens for scripts and mobile apps (
Authorization: Bearer), with abilities. - Two-factor authentication with authenticator apps and recovery codes.
- Social login with GitHub, Google, Microsoft, and other OAuth providers.
Complete Example: Generated Login Flow
Follow application creation, including dotblaze make:auth. It supplies complete login/register requests, controllers, Blade forms, password confirmation, reset, verification, social login, and two-factor challenge routes. Run:
dotblaze migrate
dotblaze db:seed
dotblaze route:list
dotblaze serveOpen /login, use test@example.com / password, and visit the walkthrough's /posts. To show the login state, add this inside the Blade layout's body:
@auth
<p>Signed in as {{ Auth.User<Blog.Models.User>()!.Name }}</p>
<form method="post" action="{{ Route('logout') }}">
@csrf
<button type="submit">Log out</button>
</form>
@else
<a href="{{ Route('login') }}">Log in</a>
@endauthExpected: the name appears after login; after logout /posts redirects to /login. Invalid credentials stay on the form with errors; repeated failures are throttled. Keep the generated Auth.Validate → TwoFactor.Challenge → Auth.Login sequence for users with two-factor authentication. Auth.Attempt is a lower-level immediate login operation, not a complete replacement for that sequence.
The sample auth controller and AuthFeaturesTest.cs provide the complete executable flow. ActingAs tests authorization but does not exercise password validation; use the generated login form or those auth tests for sign-in behavior.