Skip to content

Email Verification ​

Introduction ​

dotblaze make:auth includes Laravel Breeze's email verification: after registering, the user gets an email with a signed link, and routes with the verified middleware are closed until they click it.

Model Preparation ​

The user model implements IMustVerifyEmail and INotifiable, with an EmailVerifiedAt property:

csharp
public class User : Model<User>, IAuthenticatable, INotifiable, ICanResetPassword, IMustVerifyEmail
{
    public DateTime? EmailVerifiedAt { get; set; }
    ...
}

A user type that does not implement IMustVerifyEmail always passes the verified middleware.

Database Preparation ​

The template's users migration has the column:

csharp
t.DateTime("email_verified_at").Nullable();

Routing ​

The routes make:auth adds (in the auth group of routes/auth.cs):

csharp
Route.Get<EmailVerificationController>("/verify-email", c => c.Notice).Name("verification.notice");
Route.Get<EmailVerificationController>("/verify-email/{id}/{hash}", c => c.Verify).Name("verification.verify").Middleware("signed");
Route.Post<EmailVerificationController>("/email/verification-notification", c => c.Send).Name("verification.send");

The verified middleware redirects to verification.notice, and the email links to verification.verify, so those names are required. The registration action sends the first email:

csharp
var user = await Models.User.Create(new { request.Name, request.Email, request.Password });
await user.SendEmailVerificationNotification();
await Auth.Login(user);

The Email Verification Notice ​

csharp
public IActionResult Notice() => Auth.User<User>()!.HasVerifiedEmail() ? RedirectTo(Home) : View("auth/VerifyEmail");

The Email Verification Handler ​

The link carries the user's id, a hash of the email, an expiry, and a signature. The signed middleware rejects a tampered or expired link with 403; EmailVerification.Fulfill then checks that the id and hash belong to the logged-in user, sets EmailVerifiedAt, and dispatches Verified:

csharp
public async Task<IActionResult> Verify(string id, string hash) =>
    await EmailVerification.Fulfill(id, hash)
        ? RedirectTo(Home + "?verified=1").With("status", "Your email address has been verified.")
        : StatusCode(StatusCodes.Status403Forbidden);

Because the route also uses auth, a user who opens the link while logged out signs in first and is then sent back to it.

Resending the Verification Email ​

csharp
public async Task<IActionResult> Send()
{
    var user = Auth.User<User>()!;
    if (user.HasVerifiedEmail()) return RedirectTo(Home);

    // At most 6 emails a minute per user.
    if (!await RateLimiter.Attempt($"verify-email:{user.Id}", 6, user.SendEmailVerificationNotification))
        return Back().With("status", "Too many requests. Please wait a minute.");
    return Back().With("status", "A new verification link has been sent to your email address.");
}

Protecting Routes ​

Add verified after auth:

csharp
Route.Middleware("auth", "verified").Group(() =>
{
    Route.Resource<PostController>("/posts", parameter: "post");
});

An unverified user is redirected to verification.notice; JSON requests get 403.

Customization ​

The link expires after verification.expire minutes in config/Auth.cs (default 60). To send your own email, implement SendEmailVerificationNotification on the user model; EmailVerification.Url(user) builds the signed link.

Events ​

Verified (with the user) is dispatched when an address is verified. Listen to it like any event.

Complete Example: Protect the Blog ​

Build the complete blog, then change its existing posts group from auth to:

csharp
Route.Middleware("auth", "verified").Group(() =>
{
    Route.Resource<Blog.Controllers.PostController>("/posts", parameter: "post");
});

Run dotblaze migrate and start the application with its configured mailer. Register a new user: /posts redirects to /verify-email. Follow the signed verification link using that same user's browser session; /posts then loads. The template's factory-created seed user may already be verified, so it is not a useful manual test of the unverified redirect.

In the Blog test project, this method body checks the middleware transition:

csharp
using var app = new DotBlaze.Testing.TestApp<Program>();
await app.RefreshDatabase();
var user = await app.Run(() => Blog.Models.User.Factory()
    .Set(new { EmailVerifiedAt = (DateTime?)null }).Create());
(await app.Client().ActingAs(user).Get("/posts"))
    .AssertRedirectToRoute("verification.notice");
await app.Run(async () =>
{
    user.EmailVerifiedAt = DateTime.UtcNow;
    await user.Save();
});
(await app.Client().ActingAs(user).Get("/posts")).AssertOk();

This deliberately checks middleware, not signature validation. The full emailed-link, wrong-user, and tampering flow is exercised in AuthFeaturesTest.cs.