v1 · OpenAPI 3.1Panel

Tokenlar

Token doğrulama

Sunucu tarafınız (backend) oturum tokenlarını Fox Login'in açık anahtarlarıyla yerel olarak doğrular. API'nize gelen bir istek, Fox Login'e yapılan bir çağrıyı beklemez. Fox Login geç yanıt verdiğinde de API'niz çalışmaya devam eder.

Doğrulama kuralları

  1. Açık anahtarları https://api.foxlogin.app/.well-known/jwks.json adresinden veya https://tr.auth.foxlogin.app/.well-known/jwks.json gibi bir bölge host'undaki aynı yoldan çekin. Anahtar veya token gerekmez.
  2. Anahtar setini önbelleğe alın. Bir token daha önce görmediğiniz bir kid içerdiğinde seti bir kez yeniden çekin. Fox Login yeni anahtarları, onlarla imzalamaya başlamadan en az 24 saat önce yayınlar.
  3. Yalnızca alg: EdDSA kabul edin. none, HS256, RS256 ve diğer tüm algoritmaları reddedin.
  4. iss değerinin https://api.foxlogin.app olmasını zorunlu tutun.
  5. exp değerini, en fazla 60 saniyelik saat farkına izin vererek kontrol edin.
  6. Sunucunuz tek bir uygulamaya hizmet veriyorsa app değerinin o uygulamanın ID'sine eşit olmasını zorunlu tutun.

Anahtar seti her bölge ve sürüm için bir anahtar içerir:

GET /.well-known/jwks.json
{
  "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" }
  ]
}

Sunucu SDK'sıyla

Sunucu SDK'ları altı kuralın tamamını uygular. Anahtar setini her JWKS URL'si için bir saat önbellekte tutar ve tokenın alanlarını (claim) döndürür.

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"
    raise
claims, 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
end
use 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());
    }
}
Seçenek Varsayılan Kullanım
Uygulama ID'si yok app claim'i farklı bir uygulamayı gösteren tokenları reddedin (wrong_application).
JWKS URL'si https://api.foxlogin.app/.well-known/jwks.json Anahtarları bunun yerine bir bölge host'undan çekin.
Anahtarlar yok Testler veya çevrimdışı kullanım için anahtar setini kendiniz verin.

Her SDK bu seçenekleri kendi adlandırma stiliyle yazar, örneğin applicationId, application_id veya ApplicationID.

İmzası geçersiz olan, başka bir algoritma kullanan, issuer değeri yanlış olan veya exp zamanı geçmiş bir token 401 durum kodu ve invalid_token koduyla reddedilir. Hata mesajı nedeni içerir.

Middleware

Bearer tokenı API handler'larınız çalışmadan önce bir kez kontrol edin ve tokenın alanlarını (claim) onlara iletin:

server.tsmain.pymain.goapi/orders.phpFoxLoginFilter.javaProgram.csrequire_user.rbsrc/auth.rs
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))
}

SDK olmadan

Aynı kuralları uyguladığınız sürece Ed25519 destekleyen her JWT kütüphanesi işinizi görür. Node.js'te jose ile:

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");

SDK'lar sayfasındaki her sunucu SDK'sı aynı kontrolü yapar.

Yerel doğrulamanın göremediği durumlar

Kullanıcı çıkış yapsa, parolasını sıfırlasa veya oturumu iptal edilse bile token exp zamanına kadar geçerli kalır. Fox Login'in kendi uç noktaları böyle bir oturumu hemen reddeder, ancak sunucunuz bunu yalnızca tokenın süresi dolduğunda, yani en fazla 10 dakika sonra öğrenir. Gerekirse bu açığı nasıl kapatacağınızı Oturumlar ve çıkış sayfası anlatır.