Get started
Quick start
These steps take an empty project to a signed-in user whose token your backend checks. Pick the language your app signs users in with and the language of your backend. The code on this page and on the other docs pages follows your choice.
Samples on every docs page follow this choice.
1. Create an application
Sign in to the dashboard at app.foxlogin.app, open Applications and choose New application. Enter a name and pick the region: TR if your users are in Türkiye, EU for everyone else. The region cannot be changed later.
The new application opens on its Quick start page. It shows the application ID (app_…), the publishable key (pk_live_eu_…) and a secret key (sk_live_eu_…) named Default with the admin role.
2. Install the SDKs
Your frontend signs users in with a client SDK and the publishable key. Your backend verifies their tokens and calls the Management API with a server SDK.
npm install foxlogin
# Browser code imports "foxlogin". The same package has "foxlogin/server" for Node.js.// In Xcode: File > Add Package Dependencies, then enter the URL below.
dependencies: [
.package(url: "https://github.com/METANETSOFT/foxlogin-swift.git", from: "0.3.0"),
],
targets: [
.target(name: "MyApp", dependencies: [
.product(name: "FoxLogin", package: "foxlogin-swift"),
]),
],dependencies {
implementation("app.foxlogin:foxlogin-kotlin:0.3.0")
// The SDK's calls are suspend functions. Add coroutines if your app has none yet.
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.9.0")
}flutter pub add foxlogin
# Dart without Flutter: dart pub add foxloginnpm install foxlogin
# Node.js 20 or later. Server code imports "foxlogin/server".pip install foxlogin
# Python 3.9 or latergo get github.com/METANETSOFT/foxlogin-go
# Go 1.22 or latercomposer require metanetsoft/foxlogin
# PHP 8.1 or later, with the sodium extension (php -m | grep sodium)<!-- Java 17 or later -->
<dependency>
<groupId>app.foxlogin</groupId>
<artifactId>foxlogin</artifactId>
<version>0.3.1</version>
</dependency>dotnet add package FoxLogin
# .NET 8 or laterbundle add foxlogin
# Without Bundler: gem install foxlogin. Ruby 3.0 or later.cargo add foxlogin
cargo add tokio --features macros,rt-multi-thread3. Put the keys in your environment
Keep the keys out of your source code. The publishable key ends up in your frontend bundle or app, and that is fine. The secret key must stay in your server's environment.
# Add this file to .gitignore
FOXLOGIN_PUBLISHABLE_KEY=pk_live_eu_…
FOXLOGIN_SECRET_KEY=sk_live_eu_…
FOXLOGIN_APP_ID=app_…Bundlers expose only variables with their own prefix to the browser, such as VITE_ or NEXT_PUBLIC_. Give that prefix to the publishable key and never to the secret key. A mobile app can keep the publishable key in its build settings or in the code.
Your backend reads the secret key and the application ID from its environment. Many frameworks load .env at startup. Otherwise, export the variables in your shell or load the file with a dotenv package.
// Node.js 20.6 or later loads the file itself: node --env-file=.env server.js
const secretKey = process.env.FOXLOGIN_SECRET_KEY;
const appId = process.env.FOXLOGIN_APP_ID;import os
secret_key = os.environ["FOXLOGIN_SECRET_KEY"]
app_id = os.environ["FOXLOGIN_APP_ID"]secretKey := os.Getenv("FOXLOGIN_SECRET_KEY")
appID := os.Getenv("FOXLOGIN_APP_ID")$secretKey = getenv('FOXLOGIN_SECRET_KEY');
$appId = getenv('FOXLOGIN_APP_ID');String secretKey = System.getenv("FOXLOGIN_SECRET_KEY");
String appId = System.getenv("FOXLOGIN_APP_ID");var secretKey = Environment.GetEnvironmentVariable("FOXLOGIN_SECRET_KEY");
var appId = Environment.GetEnvironmentVariable("FOXLOGIN_APP_ID");secret_key = ENV.fetch("FOXLOGIN_SECRET_KEY")
app_id = ENV.fetch("FOXLOGIN_APP_ID")let secret_key = std::env::var("FOXLOGIN_SECRET_KEY")?;
let app_id = std::env::var("FOXLOGIN_APP_ID")?;4. Sign users up
Ask for an email, a password (8 to 256 characters) and a country. The country is an ISO 3166-1 alpha-2 code such as DE or TR, and it is required. Sign-up always answers verification_sent, also when the email already has an account, so the response never shows who is registered. Fox Login emails a six-digit code. Sending that code back creates the account and signs the user in.
import { FoxLogin } from "foxlogin";
const fox = new FoxLogin({ publishableKey: "pk_live_eu_…" });
// 1. Email a six-digit code. country is required (ISO 3166-1 alpha-2).
await fox.signUp({ email, password, country: "DE", name });
// 2. The user types the code from the email (valid 15 minutes, 5 attempts).
const result = await fox.verifySignUp({ email, code });
if (result.status === "signed_in") {
console.log(result.user.id); // "usr_eu_8f2c91a7"
}import FoxLogin
let fox = try FoxLoginClient(publishableKey: "pk_live_eu_…")
// 1. Email a six-digit code. country is required (ISO 3166-1 alpha-2).
try await fox.signUp(email: email, password: password, country: "DE", name: name)
// 2. The user types the code from the email (valid 15 minutes, 5 attempts).
let result = try await fox.verifySignUp(email: email, code: code)
if case .signedIn(let user) = result {
print(user.id) // "usr_eu_8f2c91a7"
}import app.foxlogin.FoxLoginClient
import app.foxlogin.SignInResult
val fox = FoxLoginClient(publishableKey = "pk_live_eu_…")
// Call these from a coroutine, for example in viewModelScope.launch { … }
// 1. Email a six-digit code. country is required (ISO 3166-1 alpha-2).
fox.signUp(email = email, password = password, country = "DE", name = name)
// 2. The user types the code from the email (valid 15 minutes, 5 attempts).
val result = fox.verifySignUp(email = email, code = code)
if (result is SignInResult.SignedIn) {
println(result.user.id) // "usr_eu_8f2c91a7"
}import 'package:foxlogin/foxlogin.dart';
final fox = FoxLoginClient(publishableKey: 'pk_live_eu_…');
// 1. Email a six-digit code. country is required (ISO 3166-1 alpha-2).
await fox.signUp(email: email, password: password, country: 'DE', name: name);
// 2. The user types the code from the email (valid 15 minutes, 5 attempts).
final result = await fox.verifySignUp(email: email, code: code);
if (result case SignInSuccess(:final user)) {
print(user.id); // "usr_eu_8f2c91a7"
}5. Sign users in
Returning users sign in with their password. If the user has two-factor authentication on, sign-in returns mfa_required and a token instead of a session. Ask for the code from their authenticator app and send it with that token to finish the sign-in.
const result = await fox.signIn({ email, password });
if (result.status === "mfa_required") {
// Six-digit code from the authenticator app, or one recovery code
await fox.verifyMfa({ mfaToken: result.mfaToken, code: totpCode });
}
console.log(fox.user?.email);let user: FoxUser
switch try await fox.signIn(email: email, password: password) {
case .signedIn(let signedIn):
user = signedIn
case .mfaRequired(let mfaToken):
// Six-digit code from the authenticator app, or one recovery code
user = try await fox.verifyMfa(mfaToken: mfaToken, code: totpCode)
}
print(user.email)val user = when (val result = fox.signIn(email = email, password = password)) {
is SignInResult.SignedIn -> result.user
// Six-digit code from the authenticator app, or one recovery code
is SignInResult.MfaRequired -> fox.verifyMfa(mfaToken = result.mfaToken, code = totpCode)
}
println(user.email)final user = switch (await fox.signIn(email: email, password: password)) {
SignInSuccess(:final user) => user,
// Six-digit code from the authenticator app, or one recovery code
MfaRequired(:final mfaToken) => await fox.verifyMfa(mfaToken: mfaToken, code: totpCode),
};
print(user.email);6. Send the token to your backend
The client SDK returns a valid access token, refreshing it first when it expires in less than 60 seconds. When nobody is signed in, there is no token. Send the token as a Bearer token with every request to your API.
const token = await fox.getToken();
const res = await fetch("/api/orders", {
headers: { Authorization: `Bearer ${token}` },
});guard let token = try await fox.getToken() else { return } // nil when signed out
var request = URLRequest(url: URL(string: "https://anka.io/api/orders")!)
request.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
let (data, _) = try await URLSession.shared.data(for: request)import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import okhttp3.OkHttpClient
import okhttp3.Request
val token = fox.getToken() ?: return // null when signed out
val request = Request.Builder()
.url("https://anka.io/api/orders")
.header("Authorization", "Bearer $token")
.build()
val body = withContext(Dispatchers.IO) {
OkHttpClient().newCall(request).execute().use { it.body?.string() }
}import 'package:http/http.dart' as http;
final token = await fox.getToken();
if (token == null) return; // signed out
final res = await http.get(
Uri.parse('https://anka.io/api/orders'),
headers: {'Authorization': 'Bearer $token'},
);7. Verify the token on your backend
The server SDK checks the signature with Fox Login's public keys, which it fetches once and caches, so your API does not call Fox Login on each request. Pass your application ID to reject tokens from your other applications.
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))
}A failed check is a 401 error with the code invalid_token (bad signature, wrong issuer or algorithm, expired) or wrong_application.
8. Call the Management API with the secret key
When your backend needs more than the token carries, such as the user's email for a receipt, it asks the Management API with the secret key from step 3.
import { FoxLoginAdmin } from "foxlogin/server";
const admin = new FoxLoginAdmin({ secretKey: process.env.FOXLOGIN_SECRET_KEY });
const user = await admin.users.get(process.env.FOXLOGIN_APP_ID!, res.locals.claims.sub);
console.log(user.email, user.country, user.region);import os
from foxlogin import FoxLoginAdmin
admin = FoxLoginAdmin(secret_key=os.environ["FOXLOGIN_SECRET_KEY"])
user = admin.users.get(os.environ["FOXLOGIN_APP_ID"], claims["sub"])
print(user["email"], user["country"], user["region"])admin, err := foxlogin.NewAdminClient(foxlogin.AdminOptions{SecretKey: os.Getenv("FOXLOGIN_SECRET_KEY")})
if err != nil {
return err
}
user, err := admin.Users.Get(ctx, os.Getenv("FOXLOGIN_APP_ID"), claims.Subject)
if err != nil {
return err
}
fmt.Println(user.Email, user.Country, user.Region)use FoxLogin\FoxLoginAdmin;
$admin = new FoxLoginAdmin(['secretKey' => getenv('FOXLOGIN_SECRET_KEY')]);
$user = $admin->getUser(getenv('FOXLOGIN_APP_ID'), $claims->sub);
echo "{$user->email} {$user->country} {$user->region}\n";import app.foxlogin.FoxLoginAdmin;
import app.foxlogin.User;
FoxLoginAdmin admin = FoxLoginAdmin.builder(System.getenv("FOXLOGIN_SECRET_KEY")).build();
User user = admin.users().get(System.getenv("FOXLOGIN_APP_ID"), claims.sub());
System.out.println(user.email() + " " + user.country() + " " + user.region());var admin = new FoxLoginAdminClient(new FoxLoginAdminClientOptions
{
SecretKey = Environment.GetEnvironmentVariable("FOXLOGIN_SECRET_KEY"),
});
var user = await admin.GetUserAsync(Environment.GetEnvironmentVariable("FOXLOGIN_APP_ID")!, claims.Sub);
Console.WriteLine($"{user.Email} {user.Country} {user.Region}");admin = FoxLogin::Admin.new(secret_key: ENV.fetch("FOXLOGIN_SECRET_KEY"))
user = admin.users.get(ENV.fetch("FOXLOGIN_APP_ID"), claims["sub"])
puts user.values_at("email", "country", "region").join(" ")use foxlogin::AdminClient;
let admin = AdminClient::new(std::env::var("FOXLOGIN_SECRET_KEY")?)?;
let user = admin.get_user(&std::env::var("FOXLOGIN_APP_ID")?, &claims.sub).await?;
println!("{} {} {}", user.email, user.country, user.region);curl "https://api.foxlogin.app/v1/applications/$FOXLOGIN_APP_ID/users/usr_eu_8f2c91a7" \
-H "Authorization: Bearer $FOXLOGIN_SECRET_KEY"The admin client takes a secret key (sk_live_…) for one application, or an organization API key (fk_live_…) for all applications. Where an SDK has both a secret key option and an API key option, they are the same option. The server SDKs accept secret keys from version 0.3.1.
9. Store only the user ID
Save the token's sub claim next to your own records and nothing else about the person. Emails, names and password hashes stay with Fox Login in the application's region, and you fetch them when you need to show them. If a user asks you to delete their data, your own tables hold only an ID.
CREATE TABLE orders (
id bigserial PRIMARY KEY,
user_id text NOT NULL, -- "usr_eu_8f2c91a7" from claims.sub
total_cents integer NOT NULL,
created_at timestamptz NOT NULL DEFAULT now()
);Next, give each of your services its own key with the smallest role it needs: Secret key roles.