Keratin AuthN Server

repository·main·Indexed 23 days ago

https://github.com/keratin/authn-server

A modern authentication backend service written in Go that decouples authentication security from main applications. It manages login identities (usernames, passwords, and OAuth) and provides access tokens via secured public and private endpoints. It supports SQL databases (PostgreSQL, MySQL, SQLite) for long-term data and Redis for sessions and metrics, with official client libraries available for Ruby, Go, NodeJS, and JavaScript.

Tokens
17.4K
Snippets
22
Records
112
Agent score
79%

What's inside keratin-authn-server

  1. Overview of Keratin AuthN

    main

    Keratin AuthN is an accounts microservice designed to decouple authentication security from your main application. It manages login identities (usernames/passwords and optional OAuth identities) and provides access tokens to clients.

    Core Architecture

    • AuthN Server: Owns all credential data. It communicates directly with the client to minimize the host application's exposure to passwords and session tokens. It uses a SQL database (PostgreSQL, MySQL, SQLite) for long-term data and Redis for sessions and metrics.
    • Host App: Owns user-specific data (names, preferences, etc.) but not credentials. It identifies users by extracting the accountID from an access token verified via public key cryptography.
    • Client: Exchanges passwords for refresh and access tokens via the AuthN server. It then sends the access token to the host app.
  2. Integrate Keratin AuthN with your application

    main

    Keratin AuthN is a backend Go service that provides secured endpoints for accounts and passwords. It is designed to be integrated with both your application's frontend and backend.

    To facilitate this integration, Keratin provides official client libraries for several platforms:

    Backend Libraries:

    Frontend Libraries:

  3. How Users and Accounts relate

    main

    AuthN manages Accounts (the login identity). Your application manages Users (the application-specific profile).

    When an account logs in, the client receives a token containing the account's unique ID. To integrate this into your application, you should store this accountID in your local users table. This allows you to link application data (like names, time zones, or newsletter preferences) to the centralized AuthN identity.

  4. Architectural requirements for Keratin AuthN integration

    main

    Regardless of whether you use a Gateway-level or Pass-through authentication pattern, ensure the following architectural requirements are met:

    • Proxy Public Endpoints: Proxy all user-facing (public) endpoints to the AuthN service as if the AuthN service were a native part of your own API.
    • Frontend Integration: Expose login, signup, logout, and other user-facing features directly in your frontend client.
    • Private Endpoint Management: Integrate AuthN account management features—such as account locking, unlocking, and archival—through your existing users service.
  5. Understand the AuthN session model (Access and Refresh Tokens)

    main

    When a user logs in via AuthN, two distinct sessions are established:

    1. Access Token: A session with your application that expires periodically.
    2. Refresh Token: A session with AuthN that can be used to refresh the application's access token.

    To control the lifespan of these sessions, configure the following settings:

    • ACCESS_TOKEN_TTL
    • REFRESH_TOKEN_TTL
  6. Handle user profile creation during OAuth signup

    main
    When using OAuth, a user might be logging in (existing account) or signing up (new account). If your application requires additional user profile information beyond what the OAuth provider provides, you must check if the new session already has an associated user profile. If not, you should present a form to the user to collect the necessary extra details.
  7. Understand AuthN endpoint visibility and security

    main

    The AuthN server provides two types of endpoints, distinguished by their intended consumer and security requirements:

    1. Public Endpoints: Designed for direct client-side traffic (e.g., from a browser or mobile app). These endpoints rely on trusted Origin headers to mitigate CSRF attacks.
    2. Private Endpoints: Designed for backend-to-backend communication. These require HTTP Basic Auth (username and password) and must be accessed over HTTPS.
  8. Understand the JSON Envelope response format

    main

    AuthN uses a consistent JSON structure for responses based on the outcome of the request:

    Successful Requests

    Successful actions return an HTTP 2xx status code. The response body typically contains a result key containing the requested data.

    Failed Requests (Validation/Logic Errors)

    Failed actions return a 4xx or 5xx status code. The response body contains an errors key, which is an array of objects mapping specific fields to error messages in the format { "field": "...", "message": "..." }.

    Malformed Requests

    Errors caused by unsupported Content-Type headers or improperly formatted JSON/Form content return a 400 or 415 HTTP status code. In these cases, the response contains a single error key with a string description.

    // Success example
    {
      "result": {
        "id_token": "..."
      }
    }
    
    // Validation error example
    {
      "errors": [
        {"field": "username", "message": "TAKEN"},
        {"field": "password", "message": "INSECURE"}
      ]
    }
    
    // Malformed request example
    {
      "error": "invalid character '}' looking for beginning of value"
    }
  9. Synchronize user emails with AuthN

    main

    If your application uses email addresses as usernames, you must ensure that email changes in your application's user profile data are synchronized with the AuthN account data. This prevents login failures when a user updates their email address in your app but the AuthN server still holds the old one.

    To implement synchronization:

    1. Detect changes to user profile email addresses within your application.
    2. Queue a background job or thread to update the corresponding user's email address in the AuthN server.
  10. Migrate an existing application to Keratin AuthN

    main

    The migration to Keratin AuthN follows a four-step strategy designed to maintain stability and control migration speed:

    1. Implement AuthN side-by-side: Run AuthN alongside your legacy system. Use logic to detect if a user's account exists in AuthN and route requests accordingly.
    2. Create new users in AuthN: Direct all new signups to AuthN.
    3. Migrate existing users: Transition legacy accounts to AuthN (see Migrating Existing Users for details).
    4. Remove legacy system: Once all users have AuthN accounts, delete the legacy authentication logic and transition endpoints.
  11. Configure OAuth Clients

    main

    To configure OAuth providers, you must first determine your AuthN server's return URL. This is constructed by joining the AuthN server's base URL with the path /oauth/:providerName/return.

    Example for Google: https://authn.example.com/oauth/google/return.

    Most providers require a single environment variable containing the ClientID and ClientSecret joined by a colon (:).