Tokens
Verify tokens
Your backend verifies session tokens locally with Fox Login's public keys. A request to your API does not wait for a call to Fox Login, and your API keeps working when Fox Login is slow to answer.
Verification rules
- Fetch the public keys from
https://api.foxlogin.app/.well-known/jwks.json, or from the same path on a region host such ashttps://tr.auth.foxlogin.app/.well-known/jwks.json. No key or token is needed. - Cache the key set and refetch it once when a token names a
kidyou have not seen. Fox Login publishes new keys at least 24 hours before it signs with them. - Accept
alg: EdDSAonly. Rejectnone,HS256,RS256and every other algorithm. - Require
issto equalhttps://api.foxlogin.app. - Check
exp, allowing up to 60 seconds of clock skew. - If your backend serves one application, require
appto equal its ID.
The key set holds one key per region and version:
{
"keys": [
{ "kty": "OKP", "crv": "Ed25519", "x": "11qYAYKxCrfVS_7TyWQHOg7hcvPapiMlrwIaaPcHURo", "kid": "eu-v1", "use": "sig", "alg": "EdDSA" },
{ "kty": "OKP", "crv": "Ed25519", "x": "3p7bfXt9wbTTW2HC7OQ1Nz-DQ8hbeGdNrfx-FG-IK08", "kid": "tr-v1", "use": "sig", "alg": "EdDSA" }
]
}With a server SDK
The server SDKs apply all six rules. They cache the key set for an hour per JWKS URL and return the claims.
import { verifyToken, FoxLoginError } from "foxlogin/server";
try {
const claims = await verifyToken(token, { applicationId: process.env.FOXLOGIN_APP_ID });
console.log(claims.sub, claims.rgn, claims.labels);
} catch (e) {
if (e instanceof FoxLoginError) {
// e.status is 401; e.code is "invalid_token" or "wrong_application"
}
throw e;
}import os
from foxlogin import FoxLoginError, verify_token
try:
claims = verify_token(token, application_id=os.environ["FOXLOGIN_APP_ID"])
print(claims["sub"], claims["rgn"], claims["labels"])
except FoxLoginError as e:
# e.status is 401; e.code is "invalid_token" or "wrong_application"
raiseclaims, err := foxlogin.VerifyToken(ctx, token, foxlogin.VerifyOptions{
ApplicationID: os.Getenv("FOXLOGIN_APP_ID"),
})
if err != nil {
var fe *foxlogin.Error
if errors.As(err, &fe) {
// fe.Status is 401; fe.Code is "invalid_token" or "wrong_application"
}
return err
}
fmt.Println(claims.Subject, claims.Region, claims.Labels)use FoxLogin\FoxLoginError;
use FoxLogin\TokenVerifier;
try {
$claims = TokenVerifier::verifyToken($token, ['applicationId' => getenv('FOXLOGIN_APP_ID')]);
echo $claims->sub, ' ', $claims->rgn, "\n";
} catch (FoxLoginError $e) {
// $e->getStatus() is 401; $e->getErrorCode() is 'invalid_token' or 'wrong_application'
throw $e;
}import app.foxlogin.FoxLoginException;
import app.foxlogin.SessionClaims;
import app.foxlogin.TokenVerifier;
import app.foxlogin.VerifyOptions;
// Create the verifier once and reuse it: it holds the key set cache.
TokenVerifier verifier = new TokenVerifier();
try {
SessionClaims claims = verifier.verify(token, VerifyOptions.builder()
.applicationId(System.getenv("FOXLOGIN_APP_ID"))
.build());
System.out.println(claims.sub() + " " + claims.rgn() + " " + claims.labels());
} catch (FoxLoginException e) {
// e.getStatus() is 401; e.getCode() is "invalid_token" or "wrong_application"
throw e;
}using FoxLogin;
try
{
var claims = await FoxLoginTokenVerifier.VerifyTokenAsync(token, new VerifyOptions
{
ApplicationId = Environment.GetEnvironmentVariable("FOXLOGIN_APP_ID"),
});
Console.WriteLine($"{claims.Sub} {claims.Rgn} {string.Join(", ", claims.Labels)}");
}
catch (FoxLoginError e)
{
// e.Status is 401; e.Code is "invalid_token" or "wrong_application"
Console.Error.WriteLine(e.Code);
throw;
}require "foxlogin"
begin
claims = FoxLogin.verify_token(token, application_id: ENV.fetch("FOXLOGIN_APP_ID"))
puts claims.values_at("sub", "rgn", "labels").inspect
rescue FoxLogin::Error => e
# e.status is 401; e.code is "invalid_token" or "wrong_application"
raise e
enduse foxlogin::{verify_token, VerifyOptions};
// Build the options once and reuse them: they hold the key set cache.
let opts = VerifyOptions::new().application_id(std::env::var("FOXLOGIN_APP_ID")?);
match verify_token(&token, &opts).await {
Ok(claims) => println!("{} {} {:?}", claims.sub, claims.rgn, claims.labels),
Err(e) => {
// e.status is 401; e.code is "invalid_token" or "wrong_application"
return Err(e.into());
}
}| Option | Default | Use |
|---|---|---|
| Application ID | none | Reject tokens whose app claim is a different application (wrong_application). |
| JWKS URL | https://api.foxlogin.app/.well-known/jwks.json |
Fetch keys from a region host instead. |
| Keys | none | Pass a key set yourself, for tests or offline use. |
Each SDK names these options in its own style, such as applicationId, application_id or ApplicationID.
A token with a bad signature, another algorithm, the wrong issuer or a past exp fails with status 401 and code invalid_token; the error message holds the reason.
Middleware
Check the Bearer token once, before your API handlers run, and pass the claims on to them:
import express from "express";
import { verifyToken, FoxLoginError } from "foxlogin/server";
const app = express();
app.use("/api", async (req, res, next) => {
const token = req.get("authorization")?.replace(/^Bearer /, "");
if (!token) return res.status(401).json({ error: "missing_token" });
try {
res.locals.claims = await verifyToken(token, {
applicationId: process.env.FOXLOGIN_APP_ID,
});
next();
} catch (e) {
if (e instanceof FoxLoginError) return res.status(401).json({ error: e.code });
next(e);
}
});
app.get("/api/orders", async (req, res) => {
const userId = res.locals.claims.sub; // "usr_eu_8f2c91a7"
res.json(await db.orders.findMany({ where: { userId } }));
});import os
from fastapi import Depends, FastAPI, Header, HTTPException
from foxlogin import FoxLoginError, SessionClaims, verify_token
app = FastAPI()
def current_claims(authorization: str = Header(default="")) -> SessionClaims:
token = authorization.removeprefix("Bearer ")
if not token:
raise HTTPException(status_code=401, detail="missing_token")
try:
return verify_token(token, application_id=os.environ["FOXLOGIN_APP_ID"])
except FoxLoginError as e:
raise HTTPException(status_code=401, detail=e.code) from e
@app.get("/api/orders")
def orders(claims: SessionClaims = Depends(current_claims)):
user_id = claims["sub"] # "usr_eu_8f2c91a7"
return db.orders.find_many(user_id=user_id)package main
import (
"context"
"encoding/json"
"errors"
"net/http"
"os"
"strings"
foxlogin "github.com/METANETSOFT/foxlogin-go"
)
type claimsKey struct{}
func requireUser(next http.Handler) http.Handler {
opts := foxlogin.VerifyOptions{ApplicationID: os.Getenv("FOXLOGIN_APP_ID")}
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
token, ok := strings.CutPrefix(r.Header.Get("Authorization"), "Bearer ")
if !ok || token == "" {
http.Error(w, "missing_token", http.StatusUnauthorized)
return
}
claims, err := foxlogin.VerifyToken(r.Context(), token, opts)
var fe *foxlogin.Error
if errors.As(err, &fe) {
http.Error(w, fe.Code, http.StatusUnauthorized)
return
} else if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
next.ServeHTTP(w, r.WithContext(context.WithValue(r.Context(), claimsKey{}, claims)))
})
}
func orders(w http.ResponseWriter, r *http.Request) {
claims := r.Context().Value(claimsKey{}).(*foxlogin.SessionClaims)
userID := claims.Subject // "usr_eu_8f2c91a7"
json.NewEncoder(w).Encode(db.OrdersOf(userID))
}
func main() {
http.Handle("/api/orders", requireUser(http.HandlerFunc(orders)))
http.ListenAndServe(":8080", nil)
}<?php
require __DIR__ . '/../vendor/autoload.php';
use FoxLogin\FoxLoginError;
use FoxLogin\TokenVerifier;
$header = $_SERVER['HTTP_AUTHORIZATION'] ?? '';
if (!str_starts_with($header, 'Bearer ')) {
http_response_code(401);
exit(json_encode(['error' => 'missing_token']));
}
try {
$claims = TokenVerifier::verifyToken(substr($header, 7), [
'applicationId' => getenv('FOXLOGIN_APP_ID'),
]);
} catch (FoxLoginError $e) {
http_response_code(401);
exit(json_encode(['error' => $e->getErrorCode()]));
}
$userId = $claims->sub; // "usr_eu_8f2c91a7"
echo json_encode($db->ordersOf($userId));import app.foxlogin.FoxLoginException;
import app.foxlogin.TokenVerifier;
import app.foxlogin.VerifyOptions;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
@Component
public class FoxLoginFilter extends OncePerRequestFilter {
// One verifier for the app: it caches Fox Login's public keys.
private final TokenVerifier verifier = new TokenVerifier();
private final VerifyOptions options = VerifyOptions.builder()
.applicationId(System.getenv("FOXLOGIN_APP_ID"))
.build();
@Override
protected boolean shouldNotFilter(HttpServletRequest request) {
return !request.getRequestURI().startsWith("/api/");
}
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
throws ServletException, IOException {
String header = request.getHeader("Authorization");
if (header == null || !header.startsWith("Bearer ")) {
response.sendError(401, "missing_token");
return;
}
try {
request.setAttribute("claims", verifier.verify(header.substring(7), options));
} catch (FoxLoginException e) {
response.sendError(401, e.getCode());
return;
}
chain.doFilter(request, response);
}
}
// In a controller:
// @GetMapping("/api/orders")
// List<Order> orders(@RequestAttribute("claims") SessionClaims claims) {
// return orders.findByUserId(claims.sub()); // "usr_eu_8f2c91a7"
// }using FoxLogin;
using FoxLogin.Models;
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
var verify = new VerifyOptions { ApplicationId = Environment.GetEnvironmentVariable("FOXLOGIN_APP_ID") };
app.UseWhen(ctx => ctx.Request.Path.StartsWithSegments("/api"), api => api.Use(async (ctx, next) =>
{
var header = ctx.Request.Headers.Authorization.ToString();
if (!header.StartsWith("Bearer "))
{
ctx.Response.StatusCode = 401;
await ctx.Response.WriteAsJsonAsync(new { error = "missing_token" });
return;
}
try
{
ctx.Items["claims"] = await FoxLoginTokenVerifier.VerifyTokenAsync(header["Bearer ".Length..], verify);
}
catch (FoxLoginError e)
{
ctx.Response.StatusCode = 401;
await ctx.Response.WriteAsJsonAsync(new { error = e.Code });
return;
}
await next(ctx);
}));
app.MapGet("/api/orders", (HttpContext ctx) =>
{
var claims = (SessionClaims)ctx.Items["claims"]!;
var userId = claims.Sub; // "usr_eu_8f2c91a7"
return db.Orders.Where(o => o.UserId == userId);
});
app.Run();require "foxlogin"
require "json"
# Rack middleware. Rails: config.middleware.use RequireUser. Sinatra: use RequireUser.
class RequireUser
def initialize(app)
@app = app
end
def call(env)
return @app.call(env) unless env["PATH_INFO"].start_with?("/api/")
token = env["HTTP_AUTHORIZATION"].to_s.delete_prefix("Bearer ")
return unauthorized("missing_token") if token.empty?
begin
env["foxlogin.claims"] = FoxLogin.verify_token(token, application_id: ENV.fetch("FOXLOGIN_APP_ID"))
rescue FoxLogin::Error => e
return unauthorized(e.code)
end
@app.call(env)
end
private
def unauthorized(code)
[401, { "content-type" => "application/json" }, [{ error: code }.to_json]]
end
end
# In a Rails controller: user_id = request.env["foxlogin.claims"]["sub"] # "usr_eu_8f2c91a7"use std::sync::LazyLock;
use axum::{
extract::Request, http::StatusCode, middleware::{self, Next}, response::Response,
routing::get, Extension, Json, Router,
};
use foxlogin::{verify_token, SessionClaims, VerifyOptions};
// Built once: the options keep the cache of Fox Login's public keys.
static VERIFY: LazyLock<VerifyOptions> = LazyLock::new(|| {
VerifyOptions::new().application_id(std::env::var("FOXLOGIN_APP_ID").expect("FOXLOGIN_APP_ID"))
});
async fn require_user(mut req: Request, next: Next) -> Result<Response, StatusCode> {
let token = req
.headers()
.get("authorization")
.and_then(|v| v.to_str().ok())
.and_then(|v| v.strip_prefix("Bearer "))
.ok_or(StatusCode::UNAUTHORIZED)?;
let claims = verify_token(token, &VERIFY).await.map_err(|_| StatusCode::UNAUTHORIZED)?;
req.extensions_mut().insert(claims);
Ok(next.run(req).await)
}
async fn orders(Extension(claims): Extension<SessionClaims>) -> Json<Vec<Order>> {
let user_id = claims.sub; // "usr_eu_8f2c91a7"
Json(db::orders_of(&user_id).await)
}
pub fn routes() -> Router {
Router::new()
.route("/api/orders", get(orders))
.layer(middleware::from_fn(require_user))
}Without the SDK
Any JWT library that supports Ed25519 works, as long as you apply the same rules. With jose in Node.js:
import { createRemoteJWKSet, jwtVerify } from "jose";
const jwks = createRemoteJWKSet(new URL("https://api.foxlogin.app/.well-known/jwks.json"));
const { payload } = await jwtVerify(token, jwks, {
algorithms: ["EdDSA"],
issuer: "https://api.foxlogin.app",
clockTolerance: 60,
});
if (payload.app !== process.env.FOXLOGIN_APP_ID) throw new Error("Token of another application");Every server SDK on the SDKs page runs the same check.
What local verification cannot see
A token stays valid until its exp even after the user signs out, resets their password, or has their session revoked. Fox Login's own endpoints reject such a session at once, but your backend only learns of it when the token expires, at most 10 minutes later. Sessions and sign-out describes how to close that gap if you need to.