Skip to content

API Authentication ​

Introduction ​

API tokens let scripts, mobile apps, and other servers call your API as a user, like Laravel Sanctum's personal access tokens. A client sends Authorization: Bearer {token}; DotBlaze authenticates the request as the token's user, so the auth middleware, Auth.User(), policies, and everything else work as for a logged-in browser. Only a SHA-256 hash of each token is stored.

Installation ​

New applications have it: the personal_access_tokens migration, and a User model that implements IHasApiTokens:

csharp
public class User : Model<User>, IAuthenticatable, IHasApiTokens { ... }

For an older app, add the interface and a migration:

csharp
Schema.Create("personal_access_tokens", t =>
{
    t.Id();
    t.String("tokenable_type");
    t.String("tokenable_id", 64);
    t.String("name");
    t.String("token", 64).Unique();
    t.Text("abilities").Nullable();
    t.DateTime("last_used_at").Nullable();
    t.DateTime("expires_at").Nullable().Index();
    t.Timestamps();
    t.Index("tokenable_type", "tokenable_id");
});

Issuing API Tokens ​

csharp
var token = await user.CreateToken("deploy-script");
return Json(new { token = token.PlainTextToken });   // "5|Xk2...": shown once, never stored in plain text

token.AccessToken is the PersonalAccessToken row. List a user's tokens with user.Tokens() (a query), for example on a settings page.

Token Abilities ​

Abilities limit what a token may do, like OAuth scopes. The default is *, everything:

csharp
var token = await user.CreateToken("reader", ["posts:read"]);

if (user.TokenCan("posts:create")) { ... }

TokenCan is always true for a user logged in with the browser cookie, so the same code serves both. The current token is user.CurrentAccessToken() (null with the cookie).

Token Expiration ​

Tokens do not expire unless you say so: per token with CreateToken(name, abilities, expiresAt: DateTime.UtcNow.AddDays(30)), or for every token with auth.tokens.expiration (minutes after creation) in config/Auth.cs. dotblaze tokens:prune-expired --hours=24 deletes tokens that expired more than a day ago; schedule it daily.

Revoking Tokens ​

csharp
await user.Tokens().ForceDelete();                          // every token
await user.Tokens().Where(t => t.Id == id).ForceDelete();   // one
await user.CurrentAccessToken()!.Delete();                  // the one making this request

Protecting Routes ​

The auth middleware accepts a token as well as the login cookie. Check abilities with abilities (all of them) or ability (any of them):

csharp
// routes/api.cs, in the "api" group (CSRF for cookie-authenticated writes, rate limited)
Route.Middleware("auth").Group(() =>
{
    Route.Get<TokenController>("/user", c => c.Me);
    Route.Post<PostController>("/posts", c => c.Store).Middleware("abilities:posts:create");
    Route.Delete<PostController>("/posts/{post}", c => c.Destroy).Middleware("ability:posts:delete,admin");
});

A request without a valid token gets 401; a token without the ability 403 ({ "message": "Invalid ability provided." }).

Mobile Application Authentication ​

A mobile app trades the user's email and password for a token once, then sends the token with every request. From the sample app's Api/TokenController:

csharp
public sealed record TokenRequest(string Email, string Password, string DeviceName, string[]? Abilities);

public async Task<IActionResult> Store([FromBody] TokenRequest request)
{
    if (await Auth.Validate(new { request.Email, request.Password }) is not User user)
        return UnprocessableEntity(new { message = "The provided credentials are incorrect." });
    if (TwoFactor.Enabled(user))
        return StatusCode(403, new { message = "Complete two-factor authentication before issuing a token." });
    var token = await user.CreateToken(request.DeviceName, request.Abilities);
    return Json(new { token = token.PlainTextToken });
}

Auth.Validate checks the credentials without logging anyone in. Throttle the route (throttle:6,1).

The sample rejects password-only token issuance for accounts with two-factor authentication enabled. Applications requiring two-factor authentication must complete that challenge before issuing a bearer token; do not let token issuance bypass the login policy. Choose permitted abilities on the server instead of trusting arbitrary requested scopes.

Testing ​

Send the header with the test client:

csharp
var token = await app.Run(async () => (await user.CreateToken("test", ["posts:create"])).PlainTextToken);

(await app.Client().WithHeader("Authorization", "Bearer " + token).PostJson("/api/posts", new { title = "Hi", body = "..." }))
    .AssertCreated();

For a browser-style test, ActingAs(user) logs in with the cookie instead; then every ability check passes.

Complete Example: Ability-Protected Profile ​

In the Blog application, create:

csharp
// app/Http/Controllers/ProfileApiController.cs
using DotBlaze;
using Microsoft.AspNetCore.Mvc;

namespace Blog.Controllers;

public class ProfileApiController : BaseController
{
    public IActionResult Show()
    {
        var user = Auth.User<Blog.Models.User>()!;
        return Json(new { user.Id, user.Name });
    }
}

Inside the existing /api group in routes/api.cs, add:

csharp
Route.Get<Blog.Controllers.ProfileApiController>("/profile", c => c.Show)
    .Middleware("auth", "abilities:profile:read");

Create this file in the test project:

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

namespace Blog.Tests;

public class ApiTokenTest
{
    [Fact]
    public async Task Bearer_tokens_require_the_profile_ability()
    {
        using var app = new TestApp<Program>();
        await app.RefreshDatabase();
        var user = await app.Run(() => User.Factory().Create());
        var allowed = await app.Run(() => user.CreateToken("reader", ["profile:read"]));
        var denied = await app.Run(() => user.CreateToken("other", ["posts:read"]));
        (await app.Client().GetJson("/api/profile")).AssertUnauthorized();
        (await app.Client().WithHeader("Authorization", "Bearer " + denied.PlainTextToken)
            .GetJson("/api/profile")).AssertForbidden();
        (await app.Client().WithHeader("Authorization", "Bearer " + allowed.PlainTextToken)
            .GetJson("/api/profile")).AssertOk().AssertJsonPath("name", user.Name);
        await app.Run(() => allowed.AccessToken.Delete());
        (await app.Client().WithHeader("Authorization", "Bearer " + allowed.PlainTextToken)
            .GetJson("/api/profile")).AssertUnauthorized();
    }
}

Run dotnet test Blog.Tests --filter FullyQualifiedName~ApiTokenTest. This tests real token hashing, abilities, and revocation without exposing a password-only token-issuance endpoint.