Skip to content

Resetting Passwords ​

Introduction ​

dotblaze make:auth includes a complete "forgot password" flow, copied from the sample app and covered by its tests: a form to request a link by email, and a form to choose a new password. It is built on the Password broker, Laravel's Password facade.

Model Preparation ​

The user model implements ICanResetPassword and INotifiable (the link is sent as a notification), and mail must be configured:

csharp
public class User : Model<User>, IAuthenticatable, INotifiable, ICanResetPassword, IMustVerifyEmail { ... }

By default the Email property is used.

Database Preparation ​

Tokens are stored in the password_reset_tokens table, created by the template's users migration:

csharp
Schema.Create("password_reset_tokens", t =>
{
    t.String("email");
    t.String("token");
    t.DateTime("created_at").Nullable();
    t.Primary("email");
});

There is one token per email; only its SHA-256 hash is stored, and it is deleted after a successful reset.

Configuration ​

In config/Auth.cs:

csharp
passwords = new { expire = 60, throttle = 60 },

expire is how many minutes a token is valid. throttle is how many seconds a user must wait before requesting another link.

Routing ​

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

csharp
Route.Get<PasswordResetController>("/forgot-password", c => c.Forgot).Name("password.request");
Route.Post<PasswordResetController>("/forgot-password", c => c.SendLink).Name("password.email");
Route.Get<PasswordResetController>("/reset-password/{token}", c => c.Show).Name("password.reset");
Route.Post<PasswordResetController>("/reset-password", c => c.Store).Name("password.store");

The emailed link points to the password.reset route, so that name is required.

csharp
public async Task<IActionResult> SendLink(ForgotPasswordRequest request)
{
    var status = await Password.SendResetLink(new { request.Email });
    return status == PasswordStatus.ResetLinkSent
        ? Back().With("status", status.Message())
        : Back().WithErrors(new { Email = status.Message() }).WithInput();
}

SendResetLink finds the user by the given properties, creates a token, and calls the user's SendPasswordResetNotification(token), which sends the built-in ResetPassword notification. It returns a PasswordStatus: ResetLinkSent, InvalidUser, or Throttled. status.Message() gives the English message Laravel uses.

Resetting the Password ​

The reset form posts Token (from the URL), Email (pre-filled from the email query parameter), Password, and PasswordConfirmation:

csharp
public async Task<IActionResult> Store(ResetPasswordRequest request)
{
    var status = await Password.Reset(new { request.Email, request.Token, request.Password }, async (user, password) =>
    {
        // A new remember token logs out devices that were remembered with the old password.
        user.SetRememberToken(Str.Random(60));
        await ((Models.User)user).Update(new { Password = password });
    });

    return status == PasswordStatus.PasswordReset
        ? RedirectRoute("login").With("status", status.Message())
        : Back().WithErrors(new { Email = status.Message() }).WithInput();
}

Reset checks the token (it must match and be younger than expire minutes), calls your callback to save the new password, deletes the token, and dispatches the PasswordReset event. It returns PasswordReset, InvalidUser, or InvalidToken.

Customization ​

To send your own email, implement SendPasswordResetNotification on the user model:

csharp
public Task SendPasswordResetNotification(string token) =>
    this.Notify(new MyResetPassword { Token = token });

Password.CreateToken(user), Password.TokenExists(user, token), and Password.DeleteToken(user) are available for flows of your own.

Complete Example: Single-Use Reset Token ​

The generated UI is available after dotblaze make:auth: open /forgot-password, enter an existing user's email, follow the reset link from the configured mail transport, and submit matching Password / PasswordConfirmation values. For a deterministic broker check, add this to the Blog test project:

csharp
// Blog.Tests/PasswordResetTest.cs
using Blog.Models;
using DotBlaze;
using DotBlaze.Testing;
using Xunit;

namespace Blog.Tests;

public class PasswordResetTest
{
    [Fact]
    public async Task A_successful_reset_consumes_the_token()
    {
        using var app = new TestApp<Program>();
        await app.RefreshDatabase();
        await app.Run(async () =>
        {
            var user = await User.Factory().Create();
            var token = await Password.CreateToken(user);
            var status = await Password.Reset(
                new { user.Email, Token = token, Password = "replacement-password" },
                async (account, password) =>
                {
                    account.SetRememberToken(Guid.NewGuid().ToString("N"));
                    await ((User)account).Update(new { Password = password });
                });
            Assert.Equal(PasswordStatus.PasswordReset, status);
            Assert.False(await Password.TokenExists(user, token));
            await user.Refresh();
            Assert.True(Hash.Check("replacement-password", user.Password));
        });
    }
}

Run dotnet test Blog.Tests --filter FullyQualifiedName~PasswordResetTest. The form request still owns password-strength and confirmation validation; the broker check deliberately supplies valid data. To verify actual delivery, configure SMTP separately or inspect the array mailer in an HTTP test.