### Docker Compose Commands for Deployment and Management (Bash) Source: https://context7.com/keratin/authn-server/llms.txt Provides bash commands for managing the Docker Compose setup of the authn server. Includes commands to start services in detached mode, execute database migrations, and view logs. Assumes a docker-compose.yml file is present in the current directory. ```bash # Deploy with docker-compose docker-compose up -d # Run migrations docker-compose exec authn ./authn-server migrate # View logs docker-compose logs -f authn ``` -------------------------------- ### Initiate TOTP Setup Source: https://context7.com/keratin/authn-server/llms.txt Initiates the setup process for Time-based One-Time Password (TOTP) for an authenticated user, which is part of Multi-Factor Authentication (MFA). Upon initiation, the server returns a secret key and a QR code URL. This URL can be used with authenticator applications like Google Authenticator or Authy. The secret is temporarily stored in a cache (like Redis) until confirmed. ```bash # Begin TOTP setup curl -X POST https://auth.example.com/totp/new \ -H "Origin: https://app.example.com" \ -H "Cookie: authn=" ``` -------------------------------- ### JSON Envelope Examples for API Responses Source: https://github.com/keratin/authn-server/blob/main/docs/api.md Demonstrates the structure of JSON responses for successful and failed API operations. Includes examples for success with a 'result' key, general errors with an 'errors' array, and specific errors for invalid content types or malformed JSON. ```json { "result": { "id_token": "..." } } ``` ```json { "errors": [ {"field": "username", "message": "TAKEN"}, {"field": "password", "message": "INSECURE"} ] } ``` ```json { "error": "invalid character '}' looking for beginning of value" } ``` -------------------------------- ### AuthN Configuration for Passwordless Token URL (Bash) Source: https://github.com/keratin/authn-server/blob/main/docs/guide-implementing_passwordless_logins.md These examples show how to configure the APP_PASSWORDLESS_TOKEN_URL setting in AuthN. This URL points to your application's backend endpoint responsible for handling passwordless login requests. It includes examples for development and production environments. ```bash # development APP_PASSWORDLESS_TOKEN_URL=http://localhost:3000/authn/passwordless_login # production APP_PASSWORDLESS_TOKEN_URL=https://user:pass@myapp.io/authn/passwordless_login ``` -------------------------------- ### Running Database Migrations Manually (Bash) Source: https://context7.com/keratin/authn-server/llms.txt Demonstrates how to manually run database migrations for the authn server. Requires setting the DATABASE_URL environment variable and executing the migrate command from the compiled binary. Includes example output and a list of tables created by the migrations. ```bash # Run migrations manually export DATABASE_URL="postgres://user:pass@localhost/authn" ./authn-server migrate # Output: # Running migrations. # Migrations complete. # Migrations create: # - accounts table # - oauth_accounts table # - refresh_tokens table (if not using Redis) # - blobs table (if not using Redis, for TOTP cache) ``` -------------------------------- ### POST /totp/new Source: https://context7.com/keratin/authn-server/llms.txt Initiates the setup process for Time-based One-Time Password (TOTP) authentication for an authenticated user. ```APIDOC ## POST /totp/new ### Description Initiates the setup for Time-based One-Time Password (TOTP) Multi-Factor Authentication (MFA). This endpoint generates a secret key and a QR code URL that the user can use to configure their authenticator application. ### Method POST ### Endpoint https://auth.example.com/totp/new ### Parameters #### Request Headers - **Origin** (string) - Required - The origin of the request (e.g., https://app.example.com). - **Cookie** (string) - Required - Session authentication cookie (e.g., `authn=`). ### Request Example ```bash curl -X POST https://auth.example.com/totp/new \ -H "Origin: https://app.example.com" \ -H "Cookie: authn=" ``` ### Response #### Success Response (200 OK) - **secret** (string) - The TOTP secret key. - **url** (string) - The `otpauth://` URL for the QR code. #### Response Example ```json { "result": { "secret": "JBSWY3DPEHPK3PXP", "url": "otpauth://totp/user@example.com?secret=JBSWY3DPEHPK3PXP&issuer=Keratin%20AuthN" } } ``` ### Notes - The TOTP configuration follows RFC 6238 standards: SHA1 algorithm, 6 digits, 30-second period, and a 16-byte base32 encoded secret. - The generated secret is stored temporarily and is not persisted until confirmed. ``` -------------------------------- ### AuthN Configuration for Password Reset URL Source: https://github.com/keratin/authn-server/blob/main/docs/guide-implementing_forgotten_passwords.md Example configurations for the APP_PASSWORD_RESET_URL setting in AuthN. This URL points to your application's password reset endpoint. It shows examples for development and production environments. ```bash # development APP_PASSWORD_RESET_URL=http://localhost:3000/authn/password_reset # production APP_PASSWORD_RESET_URL=https://user:pass@myapp.io/authn/password_reset ``` -------------------------------- ### GET /metrics Source: https://context7.com/keratin/authn-server/llms.txt Exposes Prometheus-compatible metrics for monitoring and alerting. ```APIDOC ## GET /metrics ### Description Exposes Prometheus-compatible metrics for monitoring and alerting. ### Method GET ### Endpoint `/metrics` ### Parameters *None* ### Response #### Success Response (200) - **(text/plain)** - Prometheus metrics data. ### Response Example ```text # HELP http_requests_total Total number of HTTP requests # TYPE http_requests_total counter http_requests_total{method="POST",path="/session",status="201"} 1523 http_requests_total{method="POST",path="/session",status="422"} 89 http_requests_total{method="GET",path="/session/refresh",status="200"} 3421 # HELP authn_accounts_total Total number of accounts # TYPE authn_accounts_total gauge authn_accounts_total 5432 # Additional standard Go runtime metrics included ``` ``` -------------------------------- ### Create Account using Curl Source: https://context7.com/keratin/authn-server/llms.txt This snippet demonstrates how to create a new user account using a POST request to the Keratin AuthN Server's /accounts endpoint. It includes example JSON payload for username and password, and shows potential success and validation error responses. Requires ENABLE_SIGNUP configuration. ```bash # Create new account curl -X POST https://auth.example.com/accounts \ -H "Content-Type: application/json" \ -H "Origin: https://app.example.com" \ -d '{ "username": "user@example.com", "password": "MySecureP@ssw0rd123" }' # Response (201 Created) { "result": { "id_token": "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0IiwiYXVkIjoiYXBwLmV4YW1wbGUuY29tIiwiaXNzIjoiaHR0cHM6Ly9hdXRoLmV4YW1wbGUuY29tIiwiaWF0IjoxNjk4NzY1NDMyLCJleHAiOjE2OTg3NjkwMzIsImF1dGhfdGltZSI6MTY5ODc2NTQzMiwiYW1yIjpbInB3ZCJdfQ..." } } # Cookie set: authn=; HttpOnly; Secure; SameSite=Lax # Validation error example (422 Unprocessable Entity) { "errors": [ { "field": "password", "message": "INSECURE" } ] } ``` -------------------------------- ### Confirm TOTP Setup Source: https://context7.com/keratin/authn-server/llms.txt Confirms the Time-based One-Time Password (TOTP) setup by verifying a code provided by the user's authenticator app. If the code is valid, the encrypted TOTP secret is securely persisted to the user's account record. Future logins will then require TOTP verification. Invalid codes result in a 422 error. ```bash # Confirm TOTP with 6-digit code curl -X POST https://auth.example.com/totp/confirm \ -H "Content-Type: application/x-www-form-urlencoded" \ -H "Origin: https://app.example.com" \ -H "Cookie: authn=" \ -d "otp=123456" ``` -------------------------------- ### GET /oauth/{provider} Source: https://context7.com/keratin/authn-server/llms.txt Initiates the OAuth 2.0 login flow with a specified external provider. ```APIDOC ## GET /oauth/{provider} ### Description Initiates the OAuth 2.0 authentication flow with a third-party identity provider (e.g., Google, GitHub). The user is redirected to the provider's login page. Upon successful authentication with the provider, the user is redirected back to a specified callback URL with an authorization code. ### Method GET ### Endpoint https://auth.example.com/oauth/{provider} ### Parameters #### Path Parameters - **provider** (string) - Required - The identity provider to use (e.g., `google`, `github`, `facebook`, `discord`, `microsoft`, `apple`). #### Query Parameters - **redirect_uri** (string) - Required - The URL to which the user should be redirected after authenticating with the OAuth provider. ### Request Example ```bash # Start OAuth flow with Google curl -X GET "https://auth.example.com/oauth/google?redirect_uri=https://app.example.com/callback" \ -H "Origin: https://app.example.com" ``` ### Response #### Success Response (303 See Other) - **Location** (header) - The URL to redirect the user to, typically the OAuth provider's authorization endpoint. #### Response Example ``` Location: https://accounts.google.com/o/oauth2/v2/auth?client_id=...&redirect_uri=https://auth.example.com/oauth/google/return&response_type=code&scope=openid+email+profile&state= ``` ### OAuth Flow 1. The user clicks a link to initiate OAuth (e.g., `GET /oauth/google?redirect_uri=...`). 2. The user is redirected to the OAuth provider's login page. 3. The user authenticates with the OAuth provider. 4. The OAuth provider redirects the user back to a return URL on the AuthN server (e.g., `https://auth.example.com/oauth/google/return?code=...&state=...`). 5. The AuthN server validates the authorization code, creates or links the user account, and redirects the user to the application's callback URL, setting an authentication cookie (`authn=`). ### Supported Providers `google`, `github`, `facebook`, `discord`, `microsoft`, `apple` ### Configuration Environment variables are required for each provider's OAuth credentials (e.g., `GOOGLE_OAUTH_CREDENTIALS=client_id:client_secret`). ``` -------------------------------- ### Prometheus Metrics (Admin) Source: https://context7.com/keratin/authn-server/llms.txt Exposes Prometheus-compatible metrics for monitoring and alerting. This endpoint uses a GET request to the /metrics endpoint and includes standard Go runtime metrics. ```bash # Get Prometheus metrics curl -X GET https://auth.example.com/metrics \ -u "${HTTP_AUTH_USERNAME}:${HTTP_AUTH_PASSWORD}" # Response (200 OK, text/plain) # HELP http_requests_total Total number of HTTP requests # TYPE http_requests_total counter http_requests_total{method="POST",path="/session",status="201"} 1523 http_requests_total{method="POST",path="/session",status="422"} 89 http_requests_total{method="GET",path="/session/refresh",status="200"} 3421 # HELP authn_accounts_total Total number of accounts # TYPE authn_accounts_total gauge authn_accounts_total 5432 # Additional standard Go runtime metrics included ``` -------------------------------- ### GET /configuration Source: https://github.com/keratin/authn-server/blob/main/docs/api.md Retrieves service configuration details, primarily used by client libraries to obtain the JWKS URI. ```APIDOC ## GET /configuration ### Description Fetches essential configuration parameters for the AuthN service. This endpoint is mainly for backend client libraries to discover service details like the JWKS URI needed for JWT validation. ### Method GET ### Endpoint `/configuration` ### Response #### Success Response (200 OK) - **issuer** (string) - The base URL of the AuthN service. - **response_types_supported** (array[string]) - Supported response types, always `["id_token"]`. - **subject_types_supported** (array[string]) - Supported subject types, always `["public"]`. - **id_token_signing_alg_values_supported** (array[string]) - Supported signing algorithms, always `["RS256"]`. - **claims_supported** (array[string]) - Supported claims in tokens, always `["iss", "sub", "aud", "exp", "iat", "auth_time"]`. - **jwks_uri** (string) - The URL for the public key set used to validate JWTs issued by this service. #### Response Example ```json { "issuer": "https://authn.example.com", "response_types_supported": ["id_token"], "subject_types_supported": ["public"], "id_token_signing_alg_values_supported": ["RS256"], "claims_supported": ["iss", "sub", "aud", "exp", "iat", "auth_time"], "jwks_uri": "https://authn.example.com/.well-known/jwks.json" } ``` ``` -------------------------------- ### Docker Compose for AuthN Server and Dependencies Source: https://github.com/keratin/authn-server/blob/main/docs/guide-deploying_with_docker.md This docker-compose.yml file defines services for a MySQL database, Redis, the AuthN server, and a placeholder application. It configures inter-service communication using environment variables and specifies dependencies. This setup is suitable for local development environments requiring coordinated service deployment. ```yml version: '2' services: db: image: mysql:5.7 ports: - "3306:3306" environment: - MYSQL_ROOT_PASSWORD - MYSQL_DATABASE - MYSQL_ALLOW_EMPTY_PASSWORD=yes redis: image: redis authn: image: keratin/authn-server:1.0.0 ports: - "8765:3000" environment: - DATABASE_URL=mysql://root@db:3306/authn - REDIS_URL=redis://redis:6379/0 - AUTHN_URL=http://authn:3000 - APP_DOMAINS=localhost - SECRET_KEY_BASE depends_on: - redis - db app: # ... depends_on: - authn ``` -------------------------------- ### Get Account Details (Admin) Source: https://context7.com/keratin/authn-server/llms.txt Retrieves detailed information about a specific account using its ID. This endpoint requires HTTP Basic authentication with administrator credentials and returns account status, creation/update timestamps, and associated OAuth accounts. ```bash # Get account details curl -X GET https://auth.example.com/accounts/1234 \ -u "${HTTP_AUTH_USERNAME}:${HTTP_AUTH_PASSWORD}" # Response (200 OK) { "result": { "id": 1234, "username": "user@example.com", "locked": false, "deleted": false, "created_at": "2023-10-30T12:34:56Z", "updated_at": "2023-10-31T08:22:11Z", "last_login_at": "2023-10-31T08:22:11Z", "oauth_accounts": [ { "provider": "google", "email": "user@gmail.com" } ] } } # Error: Not found (404) { "errors": [ { "field": "account", "message": "NOT_FOUND" } ] } ``` -------------------------------- ### POST /totp/confirm Source: https://context7.com/keratin/authn-server/llms.txt Confirms the Time-based One-Time Password (TOTP) setup by verifying a code provided by the user. ```APIDOC ## POST /totp/confirm ### Description Confirms the Time-based One-Time Password (TOTP) setup by verifying a 6-digit code generated by the user's authenticator application. Upon successful confirmation, the TOTP secret is encrypted and stored with the user's account, enabling TOTP for future logins. ### Method POST ### Endpoint https://auth.example.com/totp/confirm ### Parameters #### Request Headers - **Content-Type** (string) - Required - Must be `application/x-www-form-urlencoded`. - **Origin** (string) - Required - The origin of the request (e.g., https://app.example.com). - **Cookie** (string) - Required - Session authentication cookie (e.g., `authn=`). #### Request Body - **otp** (string) - Required - The 6-digit One-Time Password from the authenticator app. ### Request Example ```bash curl -X POST https://auth.example.com/totp/confirm \ -H "Content-Type: application/x-www-form-urlencoded" \ -H "Origin: https://app.example.com" \ -H "Cookie: authn=" \ -d "otp=123456" ``` ### Response #### Success Response (200 OK) - **Empty body** - Indicates successful TOTP confirmation. TOTP is now required for subsequent logins. #### Error Response (422 Unprocessable Entity) - **errors** (array) - List of errors encountered during the process. - **field** (string) - The field associated with the error. - **message** (string) - The error message (e.g., "INVALID_OR_EXPIRED"). #### Error Example ```json { "errors": [ { "field": "otp", "message": "INVALID_OR_EXPIRED" } ] } ``` ``` -------------------------------- ### GET /stats Source: https://context7.com/keratin/authn-server/llms.txt Returns daily and weekly active user counts. Requires Redis configuration. ```APIDOC ## GET /stats ### Description Returns daily and weekly active user counts. Requires Redis configuration. ### Method GET ### Endpoint `/stats` ### Parameters *None* ### Response #### Success Response (200) - **result** (object) - Contains the active user statistics. - **actives** (object) - Contains daily and weekly active counts. - **daily** (array of objects) - Daily active user counts. - **date** (string) - The date in YYYY-MM-DD format. - **count** (integer) - The number of active users for that day. - **weekly** (array of objects) - Weekly active user counts. - **date** (string) - The week in YYYY-Www format. - **count** (integer) - The number of active users for that week. ### Response Example ```json { "result": { "actives": { "daily": [ {"date": "2023-10-31", "count": 127}, {"date": "2023-10-30", "count": 143}, {"date": "2023-10-29", "count": 156} ], "weekly": [ {"date": "2023-W44", "count": 892}, {"date": "2023-W43", "count": 867}, {"date": "2023-W42", "count": 901} ] } } } ``` ### Configuration ```bash REDIS_URL=redis://localhost:6379 DAILY_ACTIVES_RETENTION=365 # Days to retain WEEKLY_ACTIVES_RETENTION=104 # Weeks to retain ``` ``` -------------------------------- ### Login User with Curl Source: https://context7.com/keratin/authn-server/llms.txt Demonstrates logging in a user via the /session endpoint using POST requests. It shows examples for both standard username/password login and login with a Time-based One-Time Password (TOTP) for multi-factor authentication. Includes successful response and common error scenarios like invalid credentials or locked accounts. ```bash # Login with username and password curl -X POST https://auth.example.com/session \ -H "Content-Type: application/json" \ -H "Origin: https://app.example.com" \ -d '{ "username": "user@example.com", "password": "MySecureP@ssw0rd123" }' # Login with MFA (TOTP enabled) curl -X POST https://auth.example.com/session \ -H "Content-Type: application/json" \ -H "Origin: https://app.example.com" \ -d '{ "username": "user@example.com", "password": "MySecureP@ssw0rd123", "otp": "123456" }' # Response (201 Created) { "result": { "id_token": "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0IiwiYXVkIjoiYXBwLmV4YW1wbGUuY29tIiwiaXNzIjoiaHR0cHM6Ly9hdXRoLmV4YW1wbGUuY29tIiwiaWF0IjoxNjk4NzY1NDMyLCJleHAiOjE2OTg3NjkwMzIsImF1dGhfdGltZSI6MTY5ODc2NTQzMiwiYW1yIjpbInB3ZCIsIm90cCJdfQ..." } } # Error: Invalid credentials (422) { "errors": [ { "field": "credentials", "message": "FAILED" } ] } # Error: Account locked (422) { "errors": [ { "field": "account", "message": "LOCKED" } ] } ``` -------------------------------- ### Get Account Details (Admin) Source: https://context7.com/keratin/authn-server/llms.txt Retrieves detailed information about a specific account using its ID. This endpoint requires HTTP Basic authentication with administrative credentials. ```APIDOC ## GET /accounts/{id} ### Description Retrieves account information by ID. Requires HTTP Basic authentication with admin credentials. ### Method GET ### Endpoint /accounts/{id} ### Path Parameters - **id** (integer) - Required - The unique identifier of the account. ### Request Headers - **Authorization**: Required - HTTP Basic authentication header with admin credentials (e.g., `Basic base64EncodedUsernamePassword`). ### Response #### Success Response (200 OK) - **result** (object) - **id** (integer) - The account ID. - **username** (string) - The account's username. - **locked** (boolean) - Indicates if the account is locked. - **deleted** (boolean) - Indicates if the account is deleted. - **created_at** (string) - Timestamp of account creation (ISO 8601 format). - **updated_at** (string) - Timestamp of last account update (ISO 8601 format). - **last_login_at** (string) - Timestamp of the last login (ISO 8601 format). - **oauth_accounts** (array of objects) - List of linked OAuth accounts. - **provider** (string) - The OAuth provider (e.g., "google"). - **email** (string) - The email associated with the OAuth account. #### Error Response (404 Not Found) - **errors** (array of objects) - **field** (string) - Typically "account". - **message** (string) - "NOT_FOUND". ``` -------------------------------- ### Get OAuth Accounts Information Source: https://github.com/keratin/authn-server/blob/main/docs/api.md Retrieves relevant OAuth account information for the current user session. Returns a list of connected OAuth providers and their associated account identifiers and emails. Requires authentication. ```HTTP GET /oauth/accounts ``` -------------------------------- ### Get Service Configuration Source: https://github.com/keratin/authn-server/blob/main/docs/api.md Retrieves the AuthN service configuration details, primarily used by backend client libraries. It returns parameters like the issuer URL, supported response types, subject types, signing algorithms, supported claims, and the JSON Web Key Set (JWKS) URI. ```HTTP GET /configuration ``` -------------------------------- ### GET /health Endpoint for System Health Check Source: https://github.com/keratin/authn-server/blob/main/docs/api.md Checks the health of the system by verifying the status of HTTP, database, and Redis. It returns a JSON object with boolean indicators for each component, allowing external systems to determine if the service is operational. ```HTTP GET /health ``` ```JSON { "http": true, "db": true, "redis": false } ``` -------------------------------- ### Dockerfile for Building Authn Server Binary (Dockerfile) Source: https://context7.com/keratin/authn-server/llms.txt Defines a multi-stage Docker build process for the authn-server. It first builds the Go application using a Golang image and then copies the compiled binary to a minimal Alpine Linux image for a smaller final image size. Exposes port 3000 and sets the default command to run the server. ```dockerfile # Build and run with Docker FROM golang:1.13-alpine AS builder WORKDIR /app COPY go.mod go.sum ./ RUN go mod download COPY . . RUN go build -ldflags "-X main.VERSION=1.0.0" -o authn-server FROM alpine:latest RUN apk --no-cache add ca-certificates WORKDIR /root/ COPY --from=builder /app/authn-server . EXPOSE 3000 CMD ["./authn-server", "server"] ``` -------------------------------- ### Get Active User Statistics (Admin) Source: https://context7.com/keratin/authn-server/llms.txt Retrieves daily and weekly active user counts. This endpoint requires Redis configuration and uses a GET request to the /stats endpoint. ```bash # Get active user statistics curl -X GET https://auth.example.com/stats \ -u "${HTTP_AUTH_USERNAME}:${HTTP_AUTH_PASSWORD}" # Response (200 OK) { "result": { "actives": { "daily": [ {"date": "2023-10-31", "count": 127}, {"date": "2023-10-30", "count": 143}, {"date": "2023-10-29", "count": 156} ], "weekly": [ {"date": "2023-W44", "count": 892}, {"date": "2023-W43", "count": 867}, {"date": "2023-W42", "count": 901} ] } } } ``` -------------------------------- ### Signup Source: https://github.com/keratin/authn-server/blob/main/docs/api.md Allows a new user to sign up for an account. This is a public endpoint. ```APIDOC ## POST /accounts ### Description Allows a new user to sign up for an account. This is a public endpoint. ### Method POST ### Endpoint /accounts ### Parameters #### Request Body - **username** (string) - Required - Must be present and unique. - **password** (string) - Required - Must meet minimum complexity scoring per [zxcvbn](https://blogs.dropbox.com/tech/2012/04/zxcvbn-realistic-password-strength-estimation/). ### Request Example ```json { "username": "testuser", "password": "StrongPassword123!" } ``` ### Response #### Success Response (201) - **id_token** (string) - JWT token for the newly created session. #### Response Example ```json { "result": { "id_token": "..." } } ``` #### Error Response (422) - **field** (string) - The field that caused the error. - **message** (string) - The error message (e.g., MISSING, FORMAT_INVALID, TAKEN, INSECURE). #### Error Response Example ```json { "errors": [ {"field": "username", "message": "TAKEN"}, {"field": "password", "message": "INSECURE"} ] } ``` ``` -------------------------------- ### Docker Compose for Authn Server Services (YAML) Source: https://context7.com/keratin/authn-server/llms.txt Sets up a Docker Compose configuration for running the authn server, a PostgreSQL database, and Redis. It defines the services, their build context or image, ports, environment variables (including secrets from the host environment), and network dependencies. Volumes are used for persistent storage of database and Redis data. ```yaml version: '3.8' services: authn: build: . ports: - "3000:3000" environment: - DATABASE_URL=postgres://authn:password@db:5432/authn - REDIS_URL=redis://redis:6379/0 - AUTHN_URL=http://localhost:3000 - APP_DOMAINS=localhost:3001 - SECRET_KEY_BASE=${SECRET_KEY_BASE} depends_on: - db - redis db: image: postgres:13 environment: POSTGRES_USER: authn POSTGRES_PASSWORD: password POSTGRES_DB: authn volumes: - postgres_data:/var/lib/postgresql/data redis: image: redis:6-alpine volumes: - redis_data:/data volumes: postgres_data: redis_data: ``` -------------------------------- ### Get Account API Endpoint (GET /accounts/:id) Source: https://github.com/keratin/authn-server/blob/main/docs/api.md Retrieves details of a specific user account using its ID, which is derived from the JWT 'sub' claim. This private endpoint returns account information including username, associated OAuth accounts, last login time, and status flags (locked, deleted). It returns a 404 error if the account is not found. ```http GET /accounts/123 ``` ```http { "result": { "id": 123, "username": "testuser", "oauth_accounts": [ { "provider": "google", "provider_account_id": "91293", "email": "authn@keratin.com" } ], "last_login_at": "2006-01-02T15:04:05Z07:00", "password_changed_at": "2006-01-02T15:04:05Z07:00", "locked": false, "deleted": false } } ``` ```http { "errors": [ {"field": "account", "message": "NOT_FOUND"} ] } ``` -------------------------------- ### Account Creation (Sign Up) API Source: https://context7.com/keratin/authn-server/llms.txt Creates a new user account with username and password validation. Requires ENABLE_SIGNUP=true configuration. Returns a session cookie and JWT identity token upon successful creation. ```APIDOC ## POST /accounts ### Description Creates a new user account with username and password validation. Requires `ENABLE_SIGNUP=true` configuration. Returns a session cookie and JWT identity token upon successful creation. ### Method POST ### Endpoint `/accounts` ### Parameters #### Request Body - **username** (string) - Required - The username for the new account. - **password** (string) - Required - The password for the new account. ### Request Example ```json { "username": "user@example.com", "password": "MySecureP@ssw0rd123" } ``` ### Response #### Success Response (201 Created) - **result.id_token** (string) - The JWT identity token. #### Response Example ```json { "result": { "id_token": "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0IiwiYXVkIjoiYXBwLmV4YW1wbGUuY29tIiwiaXNzIjoiaHR0cHM6Ly9hdXRoLmV4YW1wbGUuY29tIiwiaWF0IjoxNjk4NzY1NDMyLCJleHAiOjE2OTg3NjkwMzIsImF1dGhfdGltZSI6MTY5ODc2NTQzMiwiYW1yIjpbInB3ZCJdfQ..." } } ``` #### Error Response (422 Unprocessable Entity) - **errors** (array) - A list of validation errors. - **field** (string) - The field with the validation error. - **message** (string) - The error message. #### Error Response Example ```json { "errors": [ { "field": "password", "message": "INSECURE" } ] } ``` ``` -------------------------------- ### Go Account Creation Service Source: https://context7.com/keratin/authn-server/llms.txt This Go code snippet outlines the signature for the AccountCreator service function. It handles the creation of new user accounts, including username format validation, length checks, password strength assessment using zxcvbn, uniqueness verification, and secure bcrypt hashing. ```go // Service function signature func AccountCreator( store data.AccountStore, config *app.Config, username string, password string, ) (*models.Account, error) // Creates account with validation: // 1. Username format (email if USERNAME_IS_EMAIL=true) // 2. Username length (min USERNAME_MIN_LENGTH) // 3. Password strength (zxcvbn score >= PASSWORD_POLICY_SCORE) // 4. Uniqueness check // 5. Bcrypt hashing (cost = BCRYPT_COST) ``` -------------------------------- ### Get Account Source: https://github.com/keratin/authn-server/blob/main/docs/api.md Retrieves details of a specific user account. This is a private endpoint. ```APIDOC ## GET /accounts/:id ### Description Retrieves details of a specific user account. This is a private endpoint. ### Method GET ### Endpoint /accounts/:id ### Parameters #### Path Parameters - **id** (integer) - Required - The ID of the account to retrieve, available from the JWT `sub` claim. ### Response #### Success Response (200) - **id** (integer) - The unique identifier of the account. - **username** (string) - The username of the account. - **oauth_accounts** (array) - A list of associated OAuth accounts. - **provider** (string) - The OAuth provider (e.g., "google", "apple"). - **provider_account_id** (string) - The unique ID provided by the OAuth provider. - **email** (string) - The email associated with the OAuth account. - **last_login_at** (string) - Timestamp of the last login. - **password_changed_at** (string) - Timestamp when the password was last changed. - **locked** (boolean) - Indicates if the account is locked. - **deleted** (boolean) - Indicates if the account is deleted. #### Response Example ```json { "result": { "id": 123, "username": "user@example.com", "oauth_accounts": [ { "provider": "google", "provider_account_id": "91293", "email": "authn@keratin.com" } ], "last_login_at": "2006-01-02T15:04:05Z07:00", "password_changed_at": "2006-01-02T15:04:05Z07:00", "locked": false, "deleted": false } } ``` #### Error Response (404) - **field** (string) - "account" - **message** (string) - "NOT_FOUND" #### Error Response Example ```json { "errors": [ {"field": "account", "message": "NOT_FOUND"} ] } ``` ``` -------------------------------- ### Account Signup API Endpoint (POST /accounts) Source: https://github.com/keratin/authn-server/blob/main/docs/api.md Handles the creation of new user accounts. This public endpoint requires a username and password, with validation for format and complexity. It returns an ID token upon successful creation or specific error messages for validation failures. ```http POST /accounts { "username": "testuser", "password": "s3cureP@ssw0rd!" } ``` ```http { "result": { "id_token": "..." } } ``` ```http { "errors": [ {"field": "username", "message": "TAKEN"}, {"field": "password", "message": "INSECURE"} ] } ``` -------------------------------- ### GET /oauth/accounts Source: https://context7.com/keratin/authn-server/llms.txt Retrieves a list of all OAuth provider accounts that are linked to the authenticated user's account. ```APIDOC ## GET /oauth/accounts ### Description Retrieves a list of all external OAuth provider accounts that have been linked to the authenticated user's profile. This allows users to see which third-party services they have connected. ### Method GET ### Endpoint https://auth.example.com/oauth/accounts ### Parameters #### Request Headers - **Origin** (string) - Required - The origin of the request (e.g., https://app.example.com). - **Cookie** (string) - Required - Session authentication cookie (e.g., `authn=`). ### Request Example ```bash curl -X GET https://auth.example.com/oauth/accounts \ -H "Origin: https://app.example.com" \ -H "Cookie: authn=" ``` ### Response #### Success Response (200 OK) - **result** (array) - A list of linked OAuth accounts. - **provider** (string) - The name of the OAuth provider. - **email** (string) - The email address associated with the linked account on that provider. #### Response Example ```json { "result": [ { "provider": "google", "email": "user@gmail.com" }, { "provider": "github", "email": "user@users.noreply.github.com" } ] } ``` ``` -------------------------------- ### Environment Variables for Authn Server Configuration (Bash) Source: https://context7.com/keratin/authn-server/llms.txt Sets essential environment variables for configuring the authn-server in a production environment. This includes database credentials, security settings, token expiry times, OAuth provider details, and webhooks. Dependencies include openssl for generating secrets. ```bash # Required core configuration export APP_DOMAINS="app.example.com,www.example.com" export AUTHN_URL="https://auth.example.com" export SECRET_KEY_BASE="$(openssl rand -hex 32)" export DATABASE_URL="postgres://authn:password@localhost:5432/authn_production?sslmode=require" # Server configuration export PORT=3000 export PUBLIC_PORT=8080 # Optional separate port for public routes # Security settings export BCRYPT_COST=12 export PASSWORD_POLICY_SCORE=3 export PASSWORD_CHANGE_LOGOUT=true # Token expiry settings (seconds) export ACCESS_TOKEN_TTL=3600 # 1 hour export REFRESH_TOKEN_TTL=2592000 # 30 days export PASSWORD_RESET_TOKEN_TTL=1800 # 30 minutes export PASSWORDLESS_TOKEN_TTL=1800 # 30 minutes # Username policy export USERNAME_IS_EMAIL=true export USERNAME_MIN_LENGTH=3 export EMAIL_USERNAME_DOMAINS="example.com,example.org" # Redis for session storage and statistics export REDIS_URL="redis://localhost:6379/0" # Admin credentials (generated if not set) export HTTP_AUTH_USERNAME="admin" export HTTP_AUTH_PASSWORD="$(openssl rand -hex 16)" # Application webhooks export APP_PASSWORD_RESET_URL="https://app.example.com/webhooks/password-reset" export APP_PASSWORD_CHANGED_URL="https://app.example.com/webhooks/password-changed" export APP_PASSWORDLESS_TOKEN_URL="https://app.example.com/webhooks/passwordless-login" # OAuth providers export GOOGLE_OAUTH_CREDENTIALS="123456789.apps.googleusercontent.com:secret123" export GITHUB_OAUTH_CREDENTIALS="abc123def456:secret789" # Error reporting export SENTRY_DSN="https://abc123@sentry.io/project" # Production settings export ENABLE_SIGNUP=false # Disable public signups export PROXIED=true # Trust X-Forwarded-For headers export SAME_SITE=STRICT # Cookie security policy # Active user tracking export DAILY_ACTIVES_RETENTION=365 export WEEKLY_ACTIVES_RETENTION=104 ``` -------------------------------- ### Run AuthN Server as Docker Daemon Source: https://github.com/keratin/authn-server/blob/main/docs/guide-deploying_with_docker.md This command runs the AuthN server as a standalone Docker container. It exposes port 8080, sets necessary environment variables for database, secrets, and authentication, and then runs migration and server commands within the container. Dependencies include Docker and the 'keratin/authn-server' image. ```sh docker run -it --rm \ --publish 8080:3000 \ -e AUTHN_URL=http://localhost:8080 \ -e APP_DOMAINS=localhost \ -e DATABASE_URL=sqlite3://:memory:?mode=memory&cache=shared \ -e SECRET_KEY_BASE=changeme \ -e HTTP_AUTH_USERNAME=hello \ -e HTTP_AUTH_PASSWORD=world \ --name authn_app \ keratin/authn-server:latest \ sh -c "./authn migrate && ./authn server" ``` -------------------------------- ### GET /jwks Source: https://github.com/keratin/authn-server/blob/main/docs/api.md Provides the public keys used by the AuthN service to sign JSON Web Tokens (JWTs). ```APIDOC ## GET /jwks ### Description Retrieves the JSON Web Key Set (JWKS) containing the public keys used by the AuthN service. This allows client applications to verify the authenticity and integrity of JWTs issued by the service. ### Method GET ### Endpoint `/jwks` ### Response #### Success Response (200 OK) - **keys** (array) - An array of public key objects. - **keys.use** (string) - Key usage, always `"sig"` (signature). - **keys.alg** (string) - The algorithm intended for use with the key, always `"RS256"`. - **keys.kty** (string) - The key type (e.g., `"RSA"`). - **keys.kid** (string) - Key ID, a unique identifier for the key. - **keys.e** (string) - The RSA public exponent. - **keys.n** (string) - The RSA modulus. #### Response Example ```json { "keys": [ { "use": "sig", "alg": "RS256", "kty": "RSA", "kid": "some-key-id", "e": "AQAB", "n": "..." } ] } ``` ``` -------------------------------- ### Go Session Verification and Creation Services Source: https://context7.com/keratin/authn-server/llms.txt This Go code provides signatures for two critical session management functions: CredentialsVerifier and SessionCreator. CredentialsVerifier handles secure authentication, including timing attack protection and optional TOTP verification. SessionCreator establishes new user sessions, issuing session and identity tokens. ```go // Credentials verification with timing attack protection func CredentialsVerifier( store data.AccountStore, config *app.Config, username string, password string, otp string, ) (*models.Account, error) // Session creation func SessionCreator( accountStore data.AccountStore, tokenStore data.RefreshTokenStore, keyStore data.KeyStore, actives data.Actives, cfg *app.Config, reporter errors.Reporter, accountID int, audience string, existingSessionToken string, amr []string, ) (string, string, error) // returns (sessionToken, identityToken, error) ``` -------------------------------- ### GET /password/reset Source: https://github.com/keratin/authn-server/blob/main/docs/api.md Requests a password reset for a given username. This initiates a process that sends a token to the user's email. ```APIDOC ## GET /password/reset ### Description Initiates the password reset process by requesting a reset token for a specified username. This endpoint should only be used if the `APP_PASSWORD_RESET_URL` configuration is set. ### Method GET ### Endpoint `/password/reset` ### Parameters #### Query Parameters - **username** (string) - Required - The username for which to request a password reset. ### Response #### Success Response (200 Ok) A webhook will be POSTed to your application's password reset URL with a request body containing: - **account_id** (integer) - Provided for your application to easily find the appropriate user. - **token** (JWT) - Your application must deliver this to the user, usually by email. This JWT's audience is AuthN, and should be opaque to your application. #### Failure Response (200 Ok) Note: Success and failure are indistinguishable to the client. The webhook is performed in the background to prevent timing attacks. ``` -------------------------------- ### OpenID Configuration Discovery Source: https://context7.com/keratin/authn-server/llms.txt Returns the OpenID Connect discovery document, which provides metadata necessary for JWT verification and client application configuration. This includes issuer details, supported response types, and JWKS URI. ```bash # Get OpenID configuration curl -X GET https://auth.example.com/configuration # Response (200 OK) { "issuer": "https://auth.example.com", "response_types_supported": ["id_token"], "subject_types_supported": ["public"], "id_token_signing_alg_values_supported": ["RS256"], "claims_supported": ["iss", "sub", "aud", "exp", "iat", "auth_time"], "jwks_uri": "https://auth.example.com/jwks" } ``` -------------------------------- ### OpenID Configuration Discovery Source: https://context7.com/keratin/authn-server/llms.txt Returns the OpenID Connect discovery document, which provides information about the issuer, supported authentication flows, and endpoints for JWT verification. ```APIDOC ## GET /configuration ### Description Returns the OpenID Connect discovery document for JWT verification and client configuration. ### Method GET ### Endpoint /configuration ### Response #### Success Response (200 OK) - **issuer** (string) - The issuer identifier of the authorization server. - **response_types_supported** (array of strings) - Supported response types. - **subject_types_supported** (array of strings) - Supported subject types. - **id_token_signing_alg_values_supported** (array of strings) - Supported signing algorithms for ID tokens. - **claims_supported** (array of strings) - Supported claims in the ID token. - **jwks_uri** (string) - The URL for the JSON Web Key Set (JWKS). ```