Protect routes in each framework
Refuse a request before the handler runs, with the idiom of each framework: middleware, a dependency, an attribute or an annotation.
What it shows
- The same API in eight frameworks, with three routes:
GET /publicfor everybody,GET /mefor a valid access token, andPUT /documents/{id}, which needsdocuments.edit. - The helper of the framework checks the bearer token before the handler runs. A missing or refused token gets
401. - The permission check runs next. A person without the permission gets
403. try.shcalls the three routes without a token, as a reader and as an editor.
The versions check a token in one of three ways. The kind of token that a version takes depends on its way:
- Express, FastAPI and Go check the token themselves, with the key set of your organization. The token must name the API in
aud: your client asks for it with the parameterresource=http://localhost:3001. The API key then asks LumoAuth whether the person that the token names holds the permission. - Laravel and Symfony ask LumoAuth about each token. The API key then asks about the person that the token names. They take both kinds of token.
- Next.js, Spring Boot and ASP.NET Core ask LumoAuth about each token, and check the permission with the token of the caller. They take the access token that your application receives at sign-in, without
resource.
Three versions add a few lines where their package has no helper:
- Laravel adds a guard that asks LumoAuth about the token. The middleware
lumoauth.permissionoflumoauth/laravelthen checks the permission. - Symfony adds a voter for
#[IsGranted]and a user provider. The token handler oflumoauth/symfony-bundlechecks the token. - Next.js adds two wrappers for route handlers, with the client of
@lumoauth/client. The root of@lumoauth/nextjsis for client components, so a route handler cannot create its client.
Before you start
- An API key with the scope
authz:check. Create it in the portal under Applications & developer tools, API keys. - The permission
documents.edit, a role that holds it, and a user who holds the role. The setup script creates the permission and the role, and gives the role to the user thatEDITOR_EMAILnames. - A second user without the role, the reader.
- An access token for each of the two users, from an application of your organization. See above for the kind of token that each version needs.
| Variable | Value |
|---|---|
LUMOAUTH_URL | The address of LumoAuth: https://app.lumoauth.dev, or https://eu.app.lumoauth.dev for the EU region. |
LUMOAUTH_ORG_ID | Your organization, for example acme-corp. |
LUMOAUTH_API_KEY | An API key with the scope authz:check. Express, FastAPI, Go, Laravel and Symfony use it to ask about the person that a token names. The setup script also needs admin:permissions:write, admin:roles:write, admin:users:read and admin:users:write. |
EDITOR_EMAIL | For the setup script: the email address of the user who tests as the editor. |
API_AUDIENCE | Optional, for Express, FastAPI and Go. The address that a token must name in aud. The default is http://localhost:3001. |
PORT | Optional. The port of the API. The default is 3001. Next.js, Laravel and Symfony take the port in their command instead. |
PERMISSION | Optional, for Express, FastAPI, Go, Next.js and ASP.NET Core. The permission of the edit route. The default is documents.edit. Spring Boot, Laravel and Symfony name it in the code instead. |
READER_TOKEN | For try.sh: an access token of a user who does not hold the permission. |
EDITOR_TOKEN | For try.sh: an access token of the editor. |
API_URL | Optional, for try.sh. The address of the running API. The default is http://localhost:3001. |
The setup script creates what the recipe needs, through the Admin API. You can run it again at any time.
EDITOR_EMAIL=erin@example.com node authorization/protect-routes/setup.mjs
setup.mjs
// Creates what the recipe needs: the permission documents.edit, a role that
// holds it, and gives the role to the person who tests as the editor. Run it
// again at any time.
//
// EDITOR_EMAIL=erin@example.com node authorization/protect-routes/setup.mjs
//
// The API key needs the scopes admin:permissions:write, admin:roles:write,
// admin:users:read and admin:users:write.
import { call, ensure, list } from '../../_lib/admin.mjs';
const email = process.env.EDITOR_EMAIL;
if (!email) {
console.error('Set EDITOR_EMAIL to the email address of an existing user.');
process.exit(1);
}
const permission = await ensure('/admin/permissions', (p) => p.slug === 'documents.edit', {
name: 'Edit documents',
slug: 'documents.edit',
description: 'Change the text of a document.',
});
const role = await ensure('/admin/roles', (r) => r.slug === 'content-editor', {
name: 'Content editor',
slug: 'content-editor',
description: 'May edit documents.',
});
await call('PUT', `/admin/roles/${role.id}/permissions`, { permissions: [permission.slug] });
const editor = (await list(`/admin/users?search=${encodeURIComponent(email)}`)).find((u) => u.email === email);
if (!editor) {
console.error(`No user has the email address ${email}.`);
process.exit(1);
}
const roles = (await call('GET', `/admin/users/${editor.id}/roles`)).data ?? [];
if (!roles.some((r) => r.slug === role.slug)) {
await call('POST', `/admin/users/${editor.id}/roles`, { roleSlug: role.slug });
}
console.log(`${email} holds the role ${role.slug}, which holds ${permission.slug}.`);
Code
Start one version of the API, then run try.sh in a second terminal.
Run each command from the recipes folder of the examples repository. Set the folder up once for your language. Every version below was run against a LumoAuth organization. Each API was run, and try.sh printed these lines against it. The Next.js version was run with next build and next start. On a new organization the setup script stops at the step that adds the new permission to the role.
- Express
- Next.js
- FastAPI
- Go net/http
- Spring Boot
- ASP.NET Core
- Laravel
- Symfony
- Try it (curl)
// An API in Express with three routes: one for everybody, one for a valid
// access token, and one that needs the permission documents.edit.
//
// node authorization/protect-routes/js/express.mjs
import express from 'express';
import { AccessTokenError, createAccessTokenVerifier, parseAuthorizationHeader } from '@lumoauth/agent';
import { LumoAuthBackend } from '@lumoauth/backend';
const issuer = `${process.env.LUMOAUTH_URL.replace(/\/+$/, '')}/orgs/${process.env.LUMOAUTH_ORG_ID}/api/v1`;
// The address of this API. A token is valid here only when its `aud` names it.
const audience = process.env.API_AUDIENCE ?? 'http://localhost:3001';
const permission = process.env.PERMISSION ?? 'documents.edit';
// The verifier checks the signature with the key set of the organization,
// and the issuer, the audience and the expiry. It keeps the key set in memory.
const verifier = createAccessTokenVerifier({ issuer, resource: audience });
// The API key asks LumoAuth about the person that the token names.
const lumo = new LumoAuthBackend({
baseUrl: process.env.LUMOAUTH_URL,
orgId: process.env.LUMOAUTH_ORG_ID,
secretKey: process.env.LUMOAUTH_API_KEY,
});
// 401 without a valid token. Otherwise `req.auth` holds the claims.
async function requireToken(req, res, next) {
const header = parseAuthorizationHeader(req.get('authorization'));
if (!header) return res.status(401).set('WWW-Authenticate', 'Bearer').json({ error: 'invalid_token' });
try {
req.auth = await verifier.verify(header.token);
next();
} catch (error) {
if (!(error instanceof AccessTokenError)) return next(error);
res.status(401).set('WWW-Authenticate', 'Bearer error="invalid_token"').json({ error: 'invalid_token' });
}
}
// 403 when the person does not hold the permission. The check runs before the handler.
const requirePermission = (slug) => async (req, res, next) => {
try {
const allowed = await lumo.permissions.check(slug, undefined, { userId: req.auth.sub });
if (!allowed) return res.status(403).json({ error: 'forbidden', permission: slug });
next();
} catch (error) {
next(error);
}
};
const app = express();
app.get('/public', (req, res) => res.json({ message: 'Hello, everybody.' }));
app.get('/me', requireToken, (req, res) => res.json({ sub: req.auth.sub }));
app.put('/documents/:id', requireToken, requirePermission(permission), (req, res) =>
res.json({ document: req.params.id, saved: true }),
);
const port = Number(process.env.PORT ?? 3001);
app.listen(port, () => console.log(`API on http://localhost:${port}`));
node authorization/protect-routes/js/express.mjs
// An API in Next.js with three routes: one for everybody, one for a valid
// access token, and one that needs the permission documents.edit. The two
// wrappers in this file ask LumoAuth about the bearer token of the request
// before the handler runs.
//
// cd authorization/protect-routes/js/nextjs && npm install && npm run dev
//
// The client comes from @lumoauth/client: the root of @lumoauth/nextjs is
// for client components, and a route handler runs on the server.
import { LumoAuth, LumoAuthApiError } from '@lumoauth/client';
type Caller = { lumo: LumoAuth; sub: string };
type Handler<C> = (request: Request, context: C & Caller) => Response | Promise<Response>;
const unauthorized = () =>
Response.json({ error: 'invalid_token' }, { status: 401, headers: { 'WWW-Authenticate': 'Bearer' } });
// LumoAuth answers 401 for a token that it does not accept.
const refused = (error: unknown) => error instanceof LumoAuthApiError && error.statusCode === 401;
// 401 without a token that LumoAuth accepts. Otherwise the handler gets the
// subject of the token, and a client that calls LumoAuth with that token.
export function withToken<C>(handler: Handler<C>) {
return async (request: Request, context: C) => {
const token = /^Bearer (\S+)$/i.exec(request.headers.get('authorization') ?? '')?.[1];
if (!token) return unauthorized();
const lumo = new LumoAuth({
baseUrl: process.env.LUMOAUTH_URL ?? 'https://app.lumoauth.dev',
orgId: process.env.LUMOAUTH_ORG_ID,
token,
});
let sub: string;
try {
({ sub } = await lumo.auth.getUserInfo(token));
} catch (error) {
if (refused(error)) return unauthorized();
throw error;
}
return handler(request, { ...context, lumo, sub });
};
}
// 403 when the caller does not hold the permission. LumoAuth checks it with
// the token of the caller.
export function withPermission<C>(slug: string, handler: Handler<C>) {
return withToken<C>(async (request, context) => {
let allowed: boolean;
try {
allowed = await context.lumo.permissions.check(slug);
} catch (error) {
if (refused(error)) return unauthorized();
throw error;
}
if (!allowed) return Response.json({ error: 'forbidden', permission: slug }, { status: 403 });
return handler(request, context);
});
}
// PUT /documents/{id}, which needs the permission documents.edit.
import { withPermission } from '../../../lib/protect';
const permission = process.env.PERMISSION ?? 'documents.edit';
export const PUT = withPermission<{ params: Promise<{ id: string }> }>(permission, async (request, { params }) => {
const { id } = await params;
return Response.json({ document: id, saved: true });
});
// GET /me, for a valid access token.
import { withToken } from '../../lib/protect';
export const GET = withToken(async (request, { sub }) => Response.json({ sub }));
// GET /public, for everybody.
export function GET() {
return Response.json({ message: 'Hello, everybody.' });
}
cd authorization/protect-routes/js/nextjs && npm install && npm run dev
"""An API in FastAPI with three routes: one for everybody, one for a valid
access token, and one that needs the permission documents.edit.
python authorization/protect-routes/python/api.py
"""
import os
import uvicorn
from fastapi import Depends, FastAPI, HTTPException
from lumoauth import LumoAuth
from lumoauth.fastapi import AccessTokenClaims, require_access_token
issuer = f"{os.environ['LUMOAUTH_URL'].rstrip('/')}/orgs/{os.environ['LUMOAUTH_ORG_ID']}/api/v1"
# The address of this API. A token is valid here only when its `aud` names it.
audience = os.environ.get("API_AUDIENCE", "http://localhost:3001")
permission = os.environ.get("PERMISSION", "documents.edit")
# The dependency checks the signature with the key set of the organization,
# and the issuer, the audience and the expiry. It answers 401 otherwise.
token = require_access_token(issuer=issuer, resource=audience)
# The API key asks LumoAuth about the person that the token names.
lumo = LumoAuth()
def require_permission(slug: str):
"""A dependency that answers 403 when the person does not hold `slug`."""
def check(claims: AccessTokenClaims = Depends(token)) -> AccessTokenClaims:
if not lumo.permissions.check(slug, user_id=claims.sub):
raise HTTPException(status_code=403, detail={"error": "forbidden", "permission": slug})
return claims
return check
app = FastAPI()
@app.get("/public")
def public():
return {"message": "Hello, everybody."}
@app.get("/me")
def me(claims: AccessTokenClaims = Depends(token)):
return {"sub": claims.sub}
@app.put("/documents/{document_id}")
def edit(document_id: str, claims: AccessTokenClaims = Depends(require_permission(permission))):
return {"document": document_id, "saved": True}
if __name__ == "__main__":
uvicorn.run(app, port=int(os.environ.get("PORT", "3001")))
python authorization/protect-routes/python/api.py
// An API with net/http and three routes: one for everybody, one for a valid
// access token, and one that needs the permission documents.edit.
//
// go run ./authorization/protect-routes/go
package main
import (
"encoding/json"
"log"
"net/http"
"os"
"strings"
lumoauth "github.com/lumoauth/lumo-auth-go"
)
func main() {
issuer := lumoauth.IssuerFor(os.Getenv("LUMOAUTH_URL"), os.Getenv("LUMOAUTH_ORG_ID"))
// The address of this API. A token is valid here only when its `aud` names it.
audience := envOr("API_AUDIENCE", "http://localhost:3001")
permission := envOr("PERMISSION", "documents.edit")
// The middleware checks the signature with the key set of the
// organization, and the issuer, the audience and the expiry. It answers
// 401 otherwise, and puts the claims into the context of the request.
requireToken := lumoauth.RequireAccessToken(lumoauth.AccessTokenVerifyOptions{Issuer: issuer, Resource: audience})
// Reads LUMOAUTH_URL, LUMOAUTH_ORG_ID and LUMOAUTH_API_KEY. The API key
// asks LumoAuth about the person that the token names.
lumo, err := lumoauth.New()
if err != nil {
log.Fatal(err)
}
// Answers 403 when the person does not hold the permission. The check
// runs before the handler.
requirePermission := func(slug string) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
claims, _ := lumoauth.AccessTokenFromContext(r.Context())
allowed, err := lumo.Permissions.Check(r.Context(), slug, &lumoauth.CheckOptions{UserID: claims.Subject})
if err != nil {
http.Error(w, "the permission check failed", http.StatusBadGateway)
return
}
if !allowed {
writeJSON(w, http.StatusForbidden, map[string]any{"error": "forbidden", "permission": slug})
return
}
next.ServeHTTP(w, r)
})
}
}
mux := http.NewServeMux()
mux.HandleFunc("GET /public", func(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, map[string]any{"message": "Hello, everybody."})
})
mux.Handle("GET /me", requireToken(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
claims, _ := lumoauth.AccessTokenFromContext(r.Context())
writeJSON(w, http.StatusOK, map[string]any{"sub": claims.Subject})
})))
mux.Handle("PUT /documents/{id}", requireToken(requirePermission(permission)(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, map[string]any{"document": r.PathValue("id"), "saved": true})
}))))
addr := ":" + envOr("PORT", "3001")
log.Printf("API on http://localhost%s", addr)
log.Fatal(http.ListenAndServe(addr, mux))
}
func envOr(name, fallback string) string {
if value := strings.TrimSpace(os.Getenv(name)); value != "" {
return value
}
return fallback
}
func writeJSON(w http.ResponseWriter, status int, body any) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
_ = json.NewEncoder(w).Encode(body)
}
go run ./authorization/protect-routes/go
// An API in Spring Boot with three routes: one for everybody, one for a valid
// access token, and one that needs the permission documents.edit.
//
// cd authorization/protect-routes/java/spring && mvn spring-boot:run
package com.example.documents;
import io.lumoauth.spring.RequirePermission;
import java.util.Map;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.oauth2.core.OAuth2AuthenticatedPrincipal;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RestController;
@SpringBootApplication
@RestController
public class DocumentsApi {
public static void main(String[] args) {
SpringApplication.run(DocumentsApi.class, args);
}
// The starter supplies the token check: it asks LumoAuth who the bearer
// token belongs to. A missing or refused token gets 401.
@Bean
SecurityFilterChain api(HttpSecurity http) throws Exception {
return http
.authorizeHttpRequests(a -> a.requestMatchers("/public").permitAll().anyRequest().authenticated())
.oauth2ResourceServer(o -> o.opaqueToken(Customizer.withDefaults()))
// A stateless API with bearer tokens: no session and no CSRF cookie.
.sessionManagement(s -> s.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.csrf(c -> c.disable())
.build();
}
@GetMapping("/public")
Map<String, Object> publicRoute() {
return Map.of("message", "Hello, everybody.");
}
@GetMapping("/me")
Map<String, Object> me(@AuthenticationPrincipal OAuth2AuthenticatedPrincipal principal) {
return Map.of("sub", principal.getName());
}
// The check runs with the token of the caller, before the method. A
// missing permission gives 403.
@RequirePermission("documents.edit")
@PutMapping("/documents/{id}")
Map<String, Object> edit(@PathVariable String id) {
return Map.of("document", id, "saved", true);
}
}
# The starter also reads LUMOAUTH_URL, LUMOAUTH_ORG_ID and LUMOAUTH_API_KEY.
lumoauth:
url: ${LUMOAUTH_URL:https://app.lumoauth.dev}
org-id: ${LUMOAUTH_ORG_ID}
api-key: ${LUMOAUTH_API_KEY}
server:
port: ${PORT:3001}
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>4.1.2</version>
<relativePath/>
</parent>
<groupId>com.example</groupId>
<artifactId>documents-api</artifactId>
<version>1.0.0</version>
<properties>
<java.version>17</java.version>
</properties>
<dependencies>
<dependency>
<groupId>io.lumoauth</groupId>
<artifactId>lumo-auth-spring-boot-starter</artifactId>
<version>1.6.0</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-oauth2-resource-server</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
cd authorization/protect-routes/java/spring && mvn spring-boot:run
#:sdk Microsoft.NET.Sdk.Web
#:package LumoAuth.AspNetCore@1.7.0
#:property PublishAot=false
// An API in ASP.NET Core with three routes: one for everybody, one for a
// valid access token, and one that needs the permission documents.edit.
//
// dotnet run authorization/protect-routes/csharp/Api.cs
using System.Security.Claims;
using LumoAuth.AspNetCore;
using LumoAuth.AspNetCore.Authentication;
using LumoAuth.AspNetCore.Authorization;
var builder = WebApplication.CreateBuilder(args);
var permission = Environment.GetEnvironmentVariable("PERMISSION") ?? "documents.edit";
var port = Environment.GetEnvironmentVariable("PORT") ?? "3001";
builder.WebHost.UseUrls($"http://localhost:{port}");
// Reads LUMOAUTH_URL, LUMOAUTH_ORG_ID and LUMOAUTH_API_KEY.
builder.Services.AddLumoAuth(builder.Configuration);
// The bearer scheme asks LumoAuth who the token belongs to, and answers 401
// for a missing or refused token.
builder.Services.AddAuthentication(LumoAuthDefaults.BearerScheme).AddLumoAuthBearer();
builder.Services.AddAuthorization();
var app = builder.Build();
app.UseAuthentication();
app.UseAuthorization();
app.MapGet("/public", () => new { message = "Hello, everybody." });
app.MapGet("/me", (ClaimsPrincipal user) => new { sub = user.FindFirstValue(ClaimTypes.NameIdentifier) })
.RequireAuthorization();
// The check runs with the token of the caller, before the handler. A missing
// permission gives 403.
app.MapPut("/documents/{id}", (string id) => new { document = id, saved = true })
.RequirePermission(permission);
app.Run();
dotnet run authorization/protect-routes/csharp/Api.cs
<?php
// An API in Laravel with three routes: one for everybody, one for a valid
// access token, and one that needs the permission documents.edit.
//
// cd authorization/protect-routes/php/laravel && composer install && php artisan serve --port=3001
//
// The package lumoauth/laravel reads LUMOAUTH_URL, LUMOAUTH_ORG_ID and
// LUMOAUTH_API_KEY. The API key asks LumoAuth about the person that the token
// names.
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
Route::get('/public', fn () => ['message' => 'Hello, everybody.']);
// The guard lumoauth answers 401 for a missing or refused token. It is
// defined in app/Providers/AppServiceProvider.php.
Route::middleware('auth:lumoauth')->group(function () {
Route::get('/me', fn (Request $request) => ['sub' => $request->user()->lumoauth_sub]);
// The middleware of the package answers 403 when the person does not
// hold the permission. The check runs before the handler.
Route::put('/documents/{id}', fn (string $id) => ['document' => $id, 'saved' => true])
->middleware('lumoauth.permission:documents.edit');
});
<?php
namespace App\Providers;
use Illuminate\Auth\GenericUser;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\ServiceProvider;
use LumoAuth\Error\LumoAuthAuthenticationError;
use LumoAuth\LumoAuth;
class AppServiceProvider extends ServiceProvider
{
public function boot(): void
{
// The guard asks LumoAuth who the bearer token belongs to. A missing
// or refused token gives no user, and auth:lumoauth answers 401.
Auth::viaRequest('lumoauth', function (Request $request) {
$token = $request->bearerToken();
if ($token === null) {
return null;
}
try {
$claims = $this->app->make(LumoAuth::class)->auth->userinfo($token);
} catch (LumoAuthAuthenticationError) {
return null;
}
// lumoauth.permission checks the LumoAuth user ID in lumoauth_sub.
return new GenericUser(['id' => $claims['sub'], 'lumoauth_sub' => $claims['sub']]);
});
}
}
<?php
// The guard of the API. Its driver, lumoauth, is defined in
// app/Providers/AppServiceProvider.php. Laravel adds its own defaults.
return [
'guards' => [
'lumoauth' => ['driver' => 'lumoauth'],
],
];
<?php
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;
return Application::configure(basePath: dirname(__DIR__))
// The routes of routes/api.php, without the prefix /api.
->withRouting(api: __DIR__.'/../routes/api.php', apiPrefix: '')
->withMiddleware(function (Middleware $middleware): void {
// An API has no sign-in page to send a guest to.
$middleware->redirectGuestsTo(fn () => null);
})
->withExceptions(function (Exceptions $exceptions): void {
// An API answers in JSON: a 401 is never a redirect to a sign-in page.
$exceptions->shouldRenderJsonWhen(fn () => true);
})->create();
{
"name": "lumoauth/recipe-protect-routes-laravel",
"description": "A Laravel API whose routes check LumoAuth tokens and permissions.",
"type": "project",
"license": "MIT",
"require": {
"php": "^8.2",
"laravel/framework": "^12.0",
"lumoauth/laravel": "^1.7"
},
"autoload": {
"psr-4": { "App\\": "app/" }
},
"scripts": {
"post-autoload-dump": [
"Illuminate\\Foundation\\ComposerScripts::postAutoloadDump",
"@php artisan package:discover --ansi"
]
},
"config": {
"allow-plugins": { "php-http/discovery": true },
"sort-packages": true
},
"minimum-stability": "stable",
"prefer-stable": true
}
cd authorization/protect-routes/php/laravel && composer install && php artisan serve --port=3001
<?php
// An API in Symfony with three routes: one for everybody, one for a valid
// access token, and one that needs the permission documents.edit. It is a
// micro kernel in one file.
//
// cd authorization/protect-routes/php/symfony && composer install && php -S localhost:3001 -t public
//
// The bundle reads LUMOAUTH_URL, LUMOAUTH_ORG_ID and LUMOAUTH_API_KEY. The API
// key asks LumoAuth about the person that the token names.
namespace App;
use LumoAuth\LumoAuth;
use LumoAuth\Symfony\LumoAuthBundle;
use LumoAuth\Symfony\Security\LumoAuthAccessTokenHandler;
use Symfony\Bundle\FrameworkBundle\FrameworkBundle;
use Symfony\Bundle\FrameworkBundle\Kernel\MicroKernelTrait;
use Symfony\Bundle\SecurityBundle\SecurityBundle;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpKernel\Kernel as BaseKernel;
use Symfony\Component\Routing\Loader\Configurator\RoutingConfigurator;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Vote;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
use Symfony\Component\Security\Core\User\InMemoryUser;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Core\User\UserProviderInterface;
use Symfony\Component\Security\Http\Attribute\CurrentUser;
use Symfony\Component\Security\Http\Attribute\IsGranted;
require_once dirname(__DIR__) . '/vendor/autoload_runtime.php';
final class Kernel extends BaseKernel
{
use MicroKernelTrait;
public function registerBundles(): iterable
{
yield new FrameworkBundle();
yield new SecurityBundle();
yield new LumoAuthBundle();
}
protected function configureContainer(ContainerConfigurator $container): void
{
$container->extension('framework', ['secret' => '%env(default::APP_SECRET)%']);
$container->extension('security', [
'providers' => ['lumoauth' => ['id' => TokenUserProvider::class]],
'firewalls' => [
'api' => [
'stateless' => true,
// The handler of the bundle asks LumoAuth who the bearer
// token belongs to. A refused token gets 401.
'access_token' => ['token_handler' => LumoAuthAccessTokenHandler::class],
],
],
// Without a token, every route except /public gets 401.
'access_control' => [
['path' => '^/public$', 'roles' => 'PUBLIC_ACCESS'],
['path' => '^/', 'roles' => 'IS_AUTHENTICATED'],
],
]);
$services = $container->services();
$services->set(TokenUserProvider::class);
$services->set(LumoAuthPermissionVoter::class)->autowire()->autoconfigure();
}
protected function configureRoutes(RoutingConfigurator $routes): void
{
$routes->add('public', '/public')->controller('kernel::publicRoute')->methods(['GET']);
$routes->add('me', '/me')->controller('kernel::me')->methods(['GET']);
$routes->add('edit', '/documents/{id}')->controller('kernel::edit')->methods(['PUT']);
}
public function publicRoute(): JsonResponse
{
return new JsonResponse(['message' => 'Hello, everybody.']);
}
public function me(#[CurrentUser] UserInterface $user): JsonResponse
{
return new JsonResponse(['sub' => $user->getUserIdentifier()]);
}
// The voter below answers before the action runs. A missing permission
// gives 403.
#[IsGranted('documents.edit')]
public function edit(string $id): JsonResponse
{
return new JsonResponse(['document' => $id, 'saved' => true]);
}
// The cache stays out of the project folder.
public function getCacheDir(): string
{
return sys_get_temp_dir() . '/lumoauth-recipe-protect-routes/cache';
}
public function getLogDir(): string
{
return sys_get_temp_dir() . '/lumoauth-recipe-protect-routes/log';
}
}
// Asks LumoAuth whether the person that the token names holds a permission.
// A LumoAuth permission has a dot in its name, such as documents.edit.
final class LumoAuthPermissionVoter extends Voter
{
public function __construct(private readonly LumoAuth $lumo)
{
}
protected function supports(string $attribute, mixed $subject): bool
{
return str_contains($attribute, '.');
}
protected function voteOnAttribute(string $attribute, mixed $subject, TokenInterface $token, ?Vote $vote = null): bool
{
$user = $token->getUser();
// With the default settings of the bundle, the user identifier is the
// LumoAuth user ID: the claim sub.
return $user !== null && $this->lumo->permissions->check($attribute, userId: $user->getUserIdentifier());
}
}
// LumoAuth has checked the token already, so each user that it names is
// valid. The API keeps no users of its own.
final class TokenUserProvider implements UserProviderInterface
{
public function loadUserByIdentifier(string $identifier): UserInterface
{
return new InMemoryUser($identifier, null);
}
public function refreshUser(UserInterface $user): UserInterface
{
return $user;
}
public function supportsClass(string $class): bool
{
return $class === InMemoryUser::class;
}
}
return static fn (array $context) => new Kernel($context['APP_ENV'] ?? 'prod', (bool) ($context['APP_DEBUG'] ?? false));
{
"name": "lumoauth/recipe-protect-routes-symfony",
"description": "A Symfony API whose routes check LumoAuth tokens and permissions.",
"type": "project",
"license": "MIT",
"require": {
"php": ">=8.2",
"lumoauth/symfony-bundle": "^1.7",
"nyholm/psr7": "^1.8",
"symfony/framework-bundle": "^7.3",
"symfony/http-client": "^7.3",
"symfony/runtime": "^7.3",
"symfony/security-bundle": "^7.3"
},
"config": {
"allow-plugins": { "php-http/discovery": false, "symfony/runtime": true },
"sort-packages": true
},
"extra": {
"runtime": { "dotenv_path": null }
}
}
cd authorization/protect-routes/php/symfony && composer install && php -S localhost:3001 -t public
#!/bin/sh
# Call the three routes of any version of the API, with curl: without a token,
# as a reader, and as an editor. Prints the status of each answer.
#
# sh authorization/protect-routes/http/try.sh
set -eu
API="${API_URL:-http://localhost:3001}"
call() {
label="$1"; method="$2"; path="$3"; token="${4:-}"
if [ -n "$token" ]; then
status=$(curl --silent --output /dev/null --write-out '%{http_code}' --request "$method" "$API$path" \
--header "Authorization: Bearer $token")
else
status=$(curl --silent --output /dev/null --write-out '%{http_code}' --request "$method" "$API$path")
fi
echo "$label: $status"
}
call "public, no token" GET /public
call "me, no token" GET /me
call "me, reader" GET /me "$READER_TOKEN"
call "edit, reader" PUT /documents/q4-report "$READER_TOKEN"
call "edit, editor" PUT /documents/q4-report "$EDITOR_TOKEN"
sh authorization/protect-routes/http/try.sh
Check the result
public, no token: 200
me, no token: 401
me, reader: 200
edit, reader: 403
edit, editor: 200
- Send a token of the wrong kind. Express, FastAPI and Go answer
401for a token without your API inaud. - Remove the role from the editor in the portal, and run
try.shagain:edit, editoris now403. The JavaScript SDK keeps each answer for five minutes by default, so Express can need that long. - The Test access page of the portal, under Access control, shows which role gives a person the permission.
Limits
- A permission check is a request to LumoAuth.
LumoAuthBackendkeeps answers in memory: itscacheoption sets how long, andcache: falseasks every time. - Only Express, FastAPI and Go check
aud. The other versions take every access token of your organization that LumoAuth accepts, also a token that names another API inaud. - Next.js, Spring Boot and ASP.NET Core cannot check a permission with a token that names your API in
aud: LumoAuth refuses such a token for the check. Next.js then answers401, Spring Boot answers500, and ASP.NET Core answers403. - A browser app hides buttons with the same permission, but it is your API that must refuse the request. See Show and hide UI by permission.
- To ask about any user from a backend job, see Check a permission.