Verify a personal agent's session in your API
Check the session header of each request from a personal agent, with one helper in each framework.
What it shows
- A personal agent calls
GET /api/orderswith the headersPoppy-SessionandPoppy-Version, and an access token when its user signed in. - The helper of your framework sends the method, the public URL and those headers to LumoAuth, with the scope that the route needs.
- A verified request reaches the handler, with the agent, the user, the Session and the account of the access token.
- A refused request never reaches the handler. The agent gets the response of LumoAuth unchanged: its status, its headers and its body.
Your API authenticates to LumoAuth as one of your confidential applications. It never sees the agent's keys or checks a JWT itself.
Before you start
- The Personal Agent Protocol is on for your organization, with the scope
orders:read. See Accept your customers' personal agents. - A confidential application whose allowed scopes include
poppy:verify. The setup script creates it. Its API key needsadmin:clients:write. An application without that scope gets403 insufficient_scope. PUBLIC_ORIGINis the address that agents call. The helpers build the URL from it and never from theHostheader.
| 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_CLIENT_ID | The client ID of a confidential application whose allowed scopes include poppy:verify. The setup script prints it. |
LUMOAUTH_CLIENT_SECRET | The secret of that application. The setup script prints it once, when it creates the application. |
PUBLIC_ORIGIN | The address that personal agents call, for example https://shop.example.com. The default is http://localhost:3000. |
The setup script creates what the recipe needs, through the Admin API. You can run it again at any time.
node personal-agents/verify-a-session/setup.mjs
setup.mjs
// Creates the confidential application that your API uses to ask LumoAuth
// about requests from personal agents. Its allowed scopes include
// poppy:verify. Run it again at any time: the application is created once.
//
// node personal-agents/verify-a-session/setup.mjs
//
// The API key needs the scope admin:clients:write. The client secret is
// printed once, when the application is created: keep it in your secret store.
import { call, ensure, printEnv } from '../../_lib/admin.mjs';
const application = await ensure('/admin/clients', (c) => c.name === 'Northwind Orders API', {
name: 'Northwind Orders API',
isConfidential: true,
grantTypes: ['client_credentials'],
scopes: ['poppy:verify'],
});
// Also for an application that existed before: the scope must be allowed.
await call('PATCH', `/admin/clients/${application.clientId}`, { scopes: ['poppy:verify'] });
console.log(`Application ${application.name} may call the verification endpoint.`);
printEnv({
LUMOAUTH_CLIENT_ID: application.clientId,
...(application.secret ? { LUMOAUTH_CLIENT_SECRET: application.secret } : {}),
});
Code
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 version ran against an organization with the protocol on. A request without a Poppy-Session header and one with a malformed header got the refusal of LumoAuth, relayed unchanged. A verified request needs a personal agent whose metadata document is on a public HTTPS address: none was available, so the handlers themselves did not run. The Next.js version was run with next build and next start.
- Express
- Next.js
- FastAPI
- Go net/http
- Symfony
- Laravel
- ASP.NET Core
// An Express API that personal agents call. LumoAuth verifies the
// Poppy-Session header of each request before the route runs.
//
// node personal-agents/verify-a-session/js/express.mjs
//
// PUBLIC_ORIGIN is the address that agents call, for example
// https://shop.example.com.
import express from 'express';
import { poppySession } from '@lumoauth/express';
const app = express();
// One check for each route, with the scopes that the route needs.
const poppy = (requiredScope) =>
poppySession({
baseUrl: process.env.LUMOAUTH_URL ?? 'https://app.lumoauth.dev',
organization: process.env.LUMOAUTH_ORG_ID,
clientId: process.env.LUMOAUTH_CLIENT_ID,
clientSecret: process.env.LUMOAUTH_CLIENT_SECRET,
// From configuration: the middleware never reads the Host header.
publicOrigin: process.env.PUBLIC_ORIGIN ?? 'http://localhost:3000',
requiredScope,
});
// A refused request never gets here: the agent receives the response that
// LumoAuth worded, unchanged.
app.get('/api/orders', poppy('orders:read'), (req, res) => {
const { clientId, userId, session, account } = req.poppy;
res.json({ agent: clientId, user: userId, session: session.id, account: account.sub, orders: [] });
});
app.listen(Number(process.env.PORT ?? 3000), () => console.log('Orders API ready'));
node personal-agents/verify-a-session/js/express.mjs
// A Next.js route that personal agents call. LumoAuth verifies the
// Poppy-Session header of each request before the handler runs.
//
// cd personal-agents/verify-a-session/js/nextjs && npm install && npm run dev
//
// PUBLIC_ORIGIN is the address that agents call, for example
// https://shop.example.com.
import { withPoppySession } from '@lumoauth/nextjs/server';
// A refused request never reaches the handler: the agent receives the
// response that LumoAuth worded, unchanged.
export const GET = withPoppySession(
{
domain: process.env.LUMOAUTH_URL ?? 'https://app.lumoauth.dev',
orgId: process.env.LUMOAUTH_ORG_ID,
clientId: process.env.LUMOAUTH_CLIENT_ID,
clientSecret: process.env.LUMOAUTH_CLIENT_SECRET,
// From configuration: the helper never reads the Host header.
publicOrigin: process.env.PUBLIC_ORIGIN ?? 'http://localhost:3000',
requiredScope: 'orders:read',
},
async (request, { poppy }) =>
Response.json({
agent: poppy.clientId,
user: poppy.userId,
session: poppy.session.id,
account: poppy.account!.sub,
orders: [],
}),
);
cd personal-agents/verify-a-session/js/nextjs && npm install && npm run dev
# A FastAPI API that personal agents call. LumoAuth verifies the
# Poppy-Session header of each request before the route runs.
#
# uvicorn --app-dir personal-agents/verify-a-session/python fastapi_app:app --port 3000
#
# PUBLIC_ORIGIN is the address that agents call, for example
# https://shop.example.com. The client reads LUMOAUTH_URL, LUMOAUTH_ORG_ID,
# LUMOAUTH_CLIENT_ID and LUMOAUTH_CLIENT_SECRET.
import os
from fastapi import Depends, FastAPI
from lumoauth import LumoAuth, PoppyVerification
from lumoauth.fastapi import LumoAuthPoppy
app = FastAPI()
lumo = LumoAuth()
# From configuration: the helper never reads the Host header.
poppy = LumoAuthPoppy(lumo, public_origin=os.environ.get("PUBLIC_ORIGIN", "http://localhost:3000"))
# A refused request never reaches a route: the agent receives the response
# that LumoAuth worded, unchanged.
poppy.install(app)
@app.get("/api/orders")
def orders(who: PoppyVerification = Depends(poppy.session("orders:read"))):
return {
"agent": who.client_id,
"user": who.user_id,
"session": who.session.id,
"account": who.account.sub,
"orders": [],
}
uvicorn --app-dir personal-agents/verify-a-session/python fastapi_app:app --port 3000
// A Go API that personal agents call. LumoAuth verifies the Poppy-Session
// header of each request before the handler runs.
//
// go run ./personal-agents/verify-a-session/go
//
// PUBLIC_ORIGIN is the address that agents call, for example
// https://shop.example.com. The client reads LUMOAUTH_URL and LUMOAUTH_ORG_ID.
package main
import (
"encoding/json"
"log"
"net/http"
"os"
lumoauth "github.com/lumoauth/lumo-auth-go"
)
func main() {
// The application's client ID and secret: only client.Poppy uses them.
client, err := lumoauth.New(lumoauth.WithClientCredentials(
os.Getenv("LUMOAUTH_CLIENT_ID"), os.Getenv("LUMOAUTH_CLIENT_SECRET")))
if err != nil {
log.Fatal(err)
}
publicOrigin := os.Getenv("PUBLIC_ORIGIN")
if publicOrigin == "" {
publicOrigin = "http://localhost:3000"
}
// A refused request never reaches the handler: the agent receives the
// response that LumoAuth worded, unchanged.
readOrders, err := client.Poppy.Middleware(lumoauth.PoppyMiddlewareOptions{
PublicOrigin: publicOrigin,
RequiredScope: []string{"orders:read"},
})
if err != nil {
log.Fatal(err)
}
mux := http.NewServeMux()
mux.Handle("GET /api/orders", readOrders(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
who, _ := lumoauth.PoppyFromContext(r.Context())
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]any{
"agent": who.ClientID,
"user": who.UserID,
"session": who.Session.ID,
"account": who.Account.Subject,
"orders": []any{},
})
})))
port := os.Getenv("PORT")
if port == "" {
port = "3000"
}
log.Println("Orders API ready")
log.Fatal(http.ListenAndServe(":"+port, mux))
}
go run ./personal-agents/verify-a-session/go
<?php
// A Symfony API that personal agents call, as a micro kernel in one file.
// LumoAuth verifies the Poppy-Session header of each request before the
// action runs.
//
// cd personal-agents/verify-a-session/php/symfony && composer install && php -S localhost:3000 -t public
//
// PUBLIC_ORIGIN is the address that agents call, for example
// https://shop.example.com. The bundle reads LUMOAUTH_URL, LUMOAUTH_ORG_ID,
// LUMOAUTH_CLIENT_ID and LUMOAUTH_CLIENT_SECRET.
use LumoAuth\Resource\PoppyVerification;
use LumoAuth\Symfony\LumoAuthBundle;
use LumoAuth\Symfony\Poppy\RequirePoppySession;
use Symfony\Bundle\FrameworkBundle\FrameworkBundle;
use Symfony\Bundle\FrameworkBundle\Kernel\MicroKernelTrait;
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;
require_once dirname(__DIR__) . '/vendor/autoload_runtime.php';
final class Kernel extends BaseKernel
{
use MicroKernelTrait;
public function registerBundles(): iterable
{
yield new FrameworkBundle();
yield new LumoAuthBundle();
}
protected function configureContainer(ContainerConfigurator $container): void
{
$container->parameters()->set('default_public_origin', 'http://localhost:3000');
$container->extension('framework', ['secret' => '%env(default::APP_SECRET)%']);
// From configuration: the bundle never reads the Host header.
$container->extension('lumoauth', [
'poppy' => ['public_origin' => '%env(default:default_public_origin:PUBLIC_ORIGIN)%'],
]);
}
protected function configureRoutes(RoutingConfigurator $routes): void
{
$routes->add('orders', '/api/orders')->controller('kernel::orders')->methods(['GET']);
}
// A refused request never reaches the action: the agent receives the
// response that LumoAuth worded, unchanged.
#[RequirePoppySession('orders:read')]
public function orders(PoppyVerification $who): JsonResponse
{
return new JsonResponse([
'agent' => $who->clientId,
'user' => $who->userId,
'session' => $who->session->id,
'account' => $who->account->sub,
'orders' => [],
]);
}
// The cache stays out of the project folder.
public function getCacheDir(): string
{
return sys_get_temp_dir() . '/lumoauth-recipe-verify-a-session/cache';
}
public function getLogDir(): string
{
return sys_get_temp_dir() . '/lumoauth-recipe-verify-a-session/log';
}
}
return static fn (array $context) => new Kernel($context['APP_ENV'] ?? 'prod', (bool) ($context['APP_DEBUG'] ?? false));
{
"name": "lumoauth/recipe-verify-a-session-symfony",
"description": "A Symfony API that personal agents call, with the LumoAuth bundle.",
"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/yaml": "^7.3"
},
"config": {
"allow-plugins": { "symfony/runtime": true },
"sort-packages": true
},
"extra": {
"runtime": { "dotenv_path": null }
}
}
cd personal-agents/verify-a-session/php/symfony && composer install && php -S localhost:3000 -t public
<?php
// A Laravel API that personal agents call. LumoAuth verifies the
// Poppy-Session header of each request before the route runs.
//
// cd personal-agents/verify-a-session/php/laravel && composer install && php artisan serve --port=3000
//
// The package reads LUMOAUTH_URL, LUMOAUTH_ORG_ID, LUMOAUTH_CLIENT_ID and
// LUMOAUTH_CLIENT_SECRET. config/lumoauth.php reads PUBLIC_ORIGIN.
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use LumoAuth\Laravel\Http\Middleware\RequirePoppySession;
// GET /api/orders. The parameter of the middleware is the scope that the
// route needs. A refused request never gets here: the agent receives the
// response that LumoAuth worded, unchanged.
Route::get('/orders', function (Request $request) {
$who = RequirePoppySession::verification($request);
return [
'agent' => $who->clientId,
'user' => $who->userId,
'session' => $who->session->id,
'account' => $who->account->sub,
'orders' => [],
];
})->middleware('lumoauth.poppy:orders:read');
<?php
// The address that personal agents call, for example https://shop.example.com.
// From configuration: the middleware never reads the Host header. The package
// adds its own defaults for the other settings.
return [
'poppy' => [
'public_origin' => env('PUBLIC_ORIGIN', 'http://localhost:3000'),
],
];
{
"name": "lumoauth/recipe-verify-a-session-laravel",
"description": "A Laravel API that personal agents call, with the LumoAuth package.",
"type": "project",
"license": "MIT",
"require": {
"php": "^8.2",
"laravel/framework": "^12.0",
"lumoauth/laravel": "^1.7"
},
"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 personal-agents/verify-a-session/php/laravel && composer install && php artisan serve --port=3000
#:sdk Microsoft.NET.Sdk.Web
#:package LumoAuth.AspNetCore@1.7.0
#:property PublishAot=false
// An ASP.NET Core API that personal agents call. LumoAuth verifies the
// Poppy-Session header of each request before the endpoint runs.
//
// dotnet run personal-agents/verify-a-session/csharp/OrdersApi.cs
//
// PUBLIC_ORIGIN is the address that agents call, for example
// https://shop.example.com.
using LumoAuth.AspNetCore;
using LumoAuth.AspNetCore.Poppy;
using LumoAuth.Models;
var builder = WebApplication.CreateBuilder(args);
// The package reads the "LumoAuth" section. These lines fill it from the
// same variables as the other versions of this recipe.
builder.Configuration.AddInMemoryCollection(new Dictionary<string, string?>
{
["LumoAuth:ClientId"] = Environment.GetEnvironmentVariable("LUMOAUTH_CLIENT_ID"),
["LumoAuth:ClientSecret"] = Environment.GetEnvironmentVariable("LUMOAUTH_CLIENT_SECRET"),
["LumoAuth:Poppy:PublicOrigin"] = Environment.GetEnvironmentVariable("PUBLIC_ORIGIN") ?? "http://localhost:3000",
});
builder.Services.AddLumoAuth(builder.Configuration);
var app = builder.Build();
// A refused request never reaches an endpoint: the agent receives the
// response that LumoAuth worded, unchanged.
app.UsePoppySessions();
app.MapGet("/api/orders", (HttpContext http) =>
{
PoppyVerification who = http.GetPoppyVerification()!;
return Results.Ok(new
{
agent = who.ClientId,
user = who.UserId,
session = who.Session!.Id,
account = who.Account!.Sub,
orders = Array.Empty<object>(),
});
}).RequirePoppySession("orders:read");
app.Run($"http://localhost:{Environment.GetEnvironmentVariable("PORT") ?? "3000"}");
dotnet run personal-agents/verify-a-session/csharp/OrdersApi.cs
Check the result
Start one version and send a request without the session header. LumoAuth refuses it, and the API passes the refusal on:
$ curl -i http://localhost:3000/api/orders -H 'Poppy-Version: 1.0'
HTTP/1.1 400 Bad Request
Cache-Control: no-store
Content-Type: application/json
{"error":"invalid_session","error_description":"The Poppy-Session header is missing."}
- A request from a personal agent that signed its user in reaches the handler. The answer holds the agent's
client_id, its name for the user, the id of the Session and the user's id in your organization. - The same request without an access token gets
401withWWW-Authenticate: Bearer scope="orders:read". The agent then signs its user in for that scope. - In the portal, open Personal agents, then Sessions. The Session of the agent is listed, and you can end it there. Its next request gets
session_ended.
Limits
- Pass the scope of each route. Without
requiredScope, a signed-out request reaches the handler, andaccountis empty. - A Session JWT is good for one verification. Put the helper on each route once, and do not verify the same request twice.
- Do not log the headers
Poppy-Session,AuthorizationandDPoP. They are secrets. - Spring Boot is not in this recipe. The Java SDK and its Spring Boot starter have no helper for the protocol. A Spring service can call the verification endpoint directly, as the docs show for plain HTTP.
- While the protocol is off for your organization, LumoAuth answers the verification call with
404. The helpers then answer with a server error. - An error of your own call to LumoAuth, such as a wrong client secret, is never relayed to the agent. The helpers answer with a server error.