Skip to content

OAuth Configuration

XeniazMmobugs edited this page Mar 10, 2026 · 11 revisions

OAuth Authentication Configuration πŸ”

OAuth Banner

Calibre-Web Automated supports advanced OAuth 2.0 and OpenID Connect (OIDC) authentication, allowing users to log in using external identity providers like Keycloak, Authentik, Google, Microsoft Azure AD, and many others. This guide covers everything you need to know about configuring and using OAuth authentication in CWA.


🎯 OAuth User Default Permissions

βœ… Fixed in v3.2+: OAuth users now automatically inherit all default configuration settings configured in CWA's Basic Configuration, ensuring parity with manually created users.

Default Settings Applied to New OAuth Users:

  • πŸ“Š Default Role: Configured role permissions (unless admin group override applies)
  • πŸ“‹ Sidebar View: Default sidebar visibility settings (books, series, authors, etc.)
  • 🌍 Locale: Default interface language (English, German, French, etc.)
  • πŸ“š Default Language: Default book language filter
  • 🏷️ Tag Restrictions: Default allowed/denied tags
  • πŸ“– Content Restrictions: Default allowed/denied column values (categories, publishers, etc.)
  • 🎨 Theme: Default CWA theme setting
  • πŸ“± Kobo Sync: Default Kobo integration settings

How it Works: When a new user logs in via OAuth for the first time, CWA automatically applies all default configuration settings from Admin Panel β†’ Basic Configuration β†’ Feature Configuration. This ensures OAuth users get the same default permissions and interface settings as users created manually by administrators.

Default User Permissions: Default permissions are configured in Admin Panel β†’ Edit UI Configuration

Admin Group Override: If the OAuth user is a member of the configured admin group (set in OAuth configuration), they receive admin role permissions instead of the default role, but all other default settings still apply.


πŸ”„ Authentication Mode Switching


🌟 Features Overview

CWA's OAuth implementation provides enterprise-grade authentication with the following features:

  • βœ… Auto-Discovery: Automatic endpoint configuration via OIDC metadata URLs
  • βœ… Manual Override: Full manual control over OAuth endpoints when needed
  • βœ… Field Mapping: Configurable JWT field extraction for usernames and emails
  • βœ… Custom Scopes: Flexible OAuth scope configuration
  • βœ… Admin Groups: Automatic admin role assignment based on OAuth groups
  • βœ… Group-Based Roles: Users with configured groups automatically get admin privileges
  • βœ… Built-in Providers: GitHub, Google, and one configurable Generic provider
  • βœ… Generic Provider: Support for any OAuth 2.0/OIDC compliant provider
  • βœ… Testing Tools: Built-in connection testing and validation
  • βš™οΈ Custom Branding: Configurable login button text (admin panel only, login page shows "Log in with SSO")

πŸ—οΈ System Architecture

How OAuth Works in CWA

graph LR
    A[User] -->|1. Click Login| B[CWA]
    B -->|2. Redirect| C[OAuth Provider]
    C -->|3. User Login| C
    C -->|4. Authorization Code| B
    B -->|5. Exchange Code| C
    C -->|6. Access Token| B
    B -->|7. Get User Info| C
    C -->|8. User Profile| B
    B -->|9. Create/Login User| A
Loading

Configuration Priority System

CWA uses a smart priority system for OAuth configuration:

  1. πŸ₯‡ Metadata URL (Highest Priority)

    • If provided, CWA fetches all endpoints automatically
    • Overrides all manual configuration
  2. πŸ₯ˆ Manual Endpoints (Medium Priority)

    • Individual endpoint URLs when metadata URL is not used
    • Gives full control over each OAuth endpoint
  3. πŸ₯‰ Base URL Auto-Discovery (Fallback)

    • Uses base URL + /.well-known/openid-configuration
    • Standard OIDC discovery fallback

βš™οΈ Configuration Guide

Accessing OAuth Settings

  1. Log in as an Admin user
  2. Navigate to Admin Panel β†’ Basic Configuration
  3. Scroll down to the OAuth Settings section

πŸš€ Quick Setup (Auto-Discovery)

For most OAuth providers, this is the easiest method:

  1. Get Metadata URL from your OAuth provider:

    • Keycloak: https://your-keycloak.com/realms/your-realm/.well-known/openid-configuration
    • Authentik: https://your-authentik.com/application/o/your-app/.well-known/openid-configuration
    • Google: https://accounts.google.com/.well-known/openid-configuration
    • Microsoft: https://login.microsoftonline.com/your-tenant/.well-known/openid-configuration
  2. Enter Configuration:

    Metadata URL: [paste your metadata URL here]
    OAuth Client ID: [your client ID]
    OAuth Client Secret: [your client secret]
    
  3. Test Connection: Click the "Test Metadata" button to verify the configuration

  4. Save: Click Submit to apply the configuration

πŸ”§ Advanced Setup (Manual Configuration)

For custom setups or when auto-discovery isn't available:

  1. Check "Use Manual Endpoint URLs" checkbox

  2. Configure Individual Endpoints:

    OAuth Base URL: https://your-provider.com
    Authorization Endpoint: https://your-provider.com/auth
    Token Endpoint: https://your-provider.com/token  
    UserInfo Endpoint: https://your-provider.com/userinfo
    
  3. Test Connection: Use the "Test Connection" button with your base URL

  4. Save Configuration

🎯 Field Mapping Configuration

Configure how CWA extracts user information from JWT tokens:

Field Purpose Default Value Examples
Username Field JWT claim for username preferred_username sub, username, email
Email Field JWT claim for email email mail, emailAddress, user_email
OAuth Scopes Requested permissions openid profile email Add groups for admin functionality

πŸ‘‘ Admin Group Configuration

CWA supports automatic role assignment based on OAuth provider groups:

How Group-Based Roles Work

  1. Group Detection: CWA checks the groups claim in JWT tokens from your OAuth provider
  2. Admin Assignment: Users belonging to the configured admin group automatically get admin privileges
  3. Default Role: Users without the admin group get standard user privileges
  4. Automatic Updates: Role assignment happens during every login (when group management is enabled)

Configuration Steps

  1. Enable Group-Based Management (Admin > Basic Configuration > Security Settings):

    β˜‘ Enable OAuth Group-Based Admin Role Management
    

    When enabled, admin privileges are automatically granted/revoked based on OAuth group membership. When disabled, you can manually manage admin roles in the user management panel.

  2. Enable Groups in OAuth Scopes:

    OAuth Scopes: openid profile email groups
    

    Note: The groups scope is required for group-based role assignment

  3. Set Admin Group Name:

    OAuth group for Admin: admin
    

    This should match the exact group name from your OAuth provider

Disabling Automatic Role Management

If you prefer to manually manage admin roles, you have two options:

Option 1: Use the Global Setting (Recommended)

  1. Go to Admin > Basic Configuration > Security Settings
  2. Uncheck "Enable OAuth Group-Based Admin Role Management"
  3. Manually assign admin roles in Admin > User Management

Option 2: Clear the Admin Group Field (Legacy)

  1. Go to Admin > Admin > Edit OAuth/OIDC Provider
  2. Clear the "OAuth group for Admin" field (leave it empty)
  3. Save the configuration

Both methods prevent OAuth logins from automatically revoking admin privileges when users aren't in the configured group. The global setting is recommended because it's more explicit and provides better logging.

Example JWT Token Structure

When a user logs in, CWA looks for groups in the JWT token:

{
  "sub": "user123",
  "preferred_username": "john.doe", 
  "email": "[email protected]",
  "groups": ["admin", "users", "editors"]
}

In this example, if OAuth group for Admin is set to admin, this user will get admin privileges.

Group Configuration by Provider

Provider Group Claim Configuration Notes
Keycloak groups Configure group mappings in client scopes
Authelia groups Configure group mappings in client scopes
Authentik ak_proxy.user.groups or groups Depends on configuration
Azure AD groups Requires group claims configuration
Google groups Requires Google Workspace with group API

Troubleshooting Groups

  • Users not getting admin role:
    • Verify "Enable OAuth Group-Based Admin Role Management" is checked in Security Settings
    • Verify groups is in OAuth scopes and group name matches exactly (case-insensitive)
    • Check provider configuration for group claims
  • Admin role being revoked unexpectedly:
    • If your OAuth provider doesn't return a groups claim, disable "Enable OAuth Group-Based Admin Role Management" in Security Settings
    • Manually assign admin roles in User Management panel
  • Group claim missing: Check provider configuration for group claims
  • Wrong group format: Some providers use arrays, others use strings (CWA handles both)

πŸ”§ Provider-Specific Setup Guides

Keycloak

  1. Create Client in your Keycloak realm:

    Client Type: OpenID Connect
    Client ID: calibre-web-automated
    Valid Redirect URIs: https://your-cwa-domain.com/login/generic/authorized
    

    ⚠️ Important: Replace your-cwa-domain.com with your actual CWA domain and include the port if non-standard (e.g., :8083)

  2. Get Metadata URL:

    https://your-keycloak.com/realms/your-realm/.well-known/openid-configuration
    
  3. CWA Configuration:

    OAuth Redirect Host: https://your-cwa-domain.com
    Metadata URL: [metadata URL from step 2]
    Client ID: calibre-web-automated
    Client Secret: [from Keycloak client credentials]
    OAuth Scopes: openid profile email groups
    Username Field: preferred_username
    Email Field: email
    Admin Group: admin
    

Authelia

  1. Create Client in your Authelia config:

    identity_providers:
      oidc:
        clients:
          ## Calibre-Web-Automated OIDC client
          - client_id: calibre
            client_name: Calibre-Web-Automated
            client_secret: "your-cwa-client-secret"
            public: false
            authorization_policy: two_factor
            require_pkce: false
            pkce_challenge_method: ''
            redirect_uris:
              - "https://your-cwa-domain.com/login/generic/authorized"
            scopes:
              - openid
              - profile
              - email
              - groups
            response_types:
              - code
            grant_types:
              - authorization_code
            access_token_signed_response_alg: none
            userinfo_signed_response_alg: none
            token_endpoint_auth_method: client_secret_basic
    

    ⚠️ Important: Replace your-cwa-domain.com with your actual CWA domain and include the port if non-standard (e.g., :8083)

  2. CWA Configuration:

    Metadata URL: https://[auth-domain]/.well-known/openid-configuration
    OAuth scopes: openid profile email groups
    Client ID: calibre
    Client Secret: [from Authelia client credentials]
    Username Field: preferred_username
    Email Field: email
    Admin Group: admins # Make sure this is correct or else you may be locked out
    Login Button Text: Authelia
    

Authentik

  1. Create Application:

    Name: Calibre-Web Automated
    Slug: calibre-web-automated
    Provider: OAuth2/OpenID Provider
    
  2. Create Provider:

    Authorization flow: default-authorization-flow
    Client type: Confidential
    Redirect URIs: https://your-cwa-domain.com/login/generic/authorized
    Scopes: openid profile email ak_proxy
    

    ⚠️ Important: Replace your-cwa-domain.com with your actual CWA domain and include the port if non-standard (e.g., :8083)

  3. CWA Configuration:

    OAuth Redirect Host: https://your-cwa-domain.com (your CWA instance URL)
    Metadata URL: https://your-authentik.com/application/o/calibre-web-automated/.well-known/openid-configuration  
    Client ID: [from Authentik application]
    Client Secret: [from Authentik application]
    Username Field: preferred_username
    Email Field: email
    

    ⚠️ Note: OAuth Redirect Host should be your CWA URL, not your Authentik URL!

Google OAuth

  1. Google Cloud Console:

    • Create OAuth 2.0 credentials
    • Add redirect URI: https://your-cwa-domain.com/login/generic/authorized

    ⚠️ Important: Replace your-cwa-domain.com with your actual CWA domain and include the port if non-standard (e.g., :8083)

  2. CWA Configuration:

    OAuth Redirect Host: https://your-cwa-domain.com
    Metadata URL: https://accounts.google.com/.well-known/openid-configuration
    Client ID: [your-client-id].apps.googleusercontent.com
    Client Secret: [your-client-secret]
    Username Field: email
    Email Field: email
    

Microsoft Azure AD

  1. Azure Portal:

    • Register new application
    • Add redirect URI: https://your-cwa-domain.com/login/generic/authorized
    • Generate client secret

    ⚠️ Important: Replace your-cwa-domain.com with your actual CWA domain and include the port if non-standard (e.g., :8083)

  2. CWA Configuration:

    OAuth Redirect Host: https://your-cwa-domain.com
    Metadata URL: https://login.microsoftonline.com/[tenant-id]/.well-known/openid-configuration
    Client ID: [application-id]
    Client Secret: [client-secret]
    Username Field: preferred_username
    Email Field: email
    

πŸ”— Linking Existing Accounts

If you have an existing CWA account (username/password) and want to use OAuth login, you must link your account to the OAuth provider. This is especially critical if you plan to Disable Standard Login, as you will be locked out if your account is not linked!

How to Link Your Account

  1. Log in to CWA using your standard username and password.
  2. Click on your Profile icon in the top right corner.
  3. In the Profile page, look for the "Link to [Provider Name]" button (e.g., "Link to Google", "Link to Generic OAuth").
  4. Click the button to initiate the OAuth flow.
  5. Authenticate with your provider.
  6. Once successful, your account is linked. You can now log in using the OAuth button on the login page.

⚠️ Important: Before Disabling Standard Login

DO NOT disable "Standard Login" until you have verified that your admin account is successfully linked to an OAuth provider.

If you disable standard login without linking your account:

  1. You will not be able to log in with your username/password.
  2. You will not be able to log in with OAuth (because it's not linked).
  3. You will be locked out of your instance.

Recovery from Lockout: If you accidentally lock yourself out, you will need to manually re-enable standard login by editing the database directly.


πŸ§ͺ Testing & Troubleshooting

πŸ”— Callback/Redirect URI Configuration

CRITICAL: All OAuth providers require you to configure the exact callback URI that CWA will use. The callback URI format depends on which OAuth provider you're configuring:

Provider Type Callback URI Format Example
Generic OAuth https://your-cwa-domain.com/login/generic/authorized https://library.example.com/login/generic/authorized
GitHub https://your-cwa-domain.com/login/github/authorized https://library.example.com/login/github/authorized
Google https://your-cwa-domain.com/login/google/authorized https://library.example.com/login/google/authorized

OAuth Redirect Host Configuration

NEW: CWA now includes an OAuth Redirect Host setting to prevent "invalid redirect URI" errors that can occur when accessing CWA through different hostnames or after extended periods of inactivity.

When to use OAuth Redirect Host:

  • 🌐 Accessing CWA via multiple hostnames or subdomains
  • πŸ”„ Behind reverse proxies (nginx, Apache, Caddy, etc.)
  • 🏠 Using dynamic DNS or changing IP addresses
  • ❌ Experiencing "invalid redirect URI" errors that resolve on retry

How to configure:

  1. Navigate to Admin Panel β†’ Basic Configuration β†’ OAuth Settings
  2. Find the OAuth Redirect Host field
  3. Enter your Calibre-Web Automated instance URL including protocol: https://your-cwa-domain.com
  4. Save and restart CWA

What this setting does:

  • Forces CWA to use a consistent callback URL when redirecting from OAuth providers
  • The callback URL format becomes: {OAuth Redirect Host}/login/{provider}/authorized
  • Example: If you set https://library.example.com, the callback becomes https://library.example.com/login/generic/authorized
  • This callback URL is what you configure in your OAuth provider's settings

Example configurations:

βœ… Correct: https://cwa.example.com (your CWA instance)
βœ… Correct: https://cwa.mydomain.org:8083 (your CWA instance)
βœ… Correct: https://192.168.1.100:8083 (your CWA instance)
❌ Wrong: https://auth.mydomain.com (OAuth provider domain)
❌ Wrong: https://keycloak.example.com (OAuth provider domain)  
❌ Wrong: cwa.example.com (missing protocol)
❌ Wrong: http://cwa.example.com/path (includes path)

⚠️ CRITICAL: The OAuth Redirect Host must be your Calibre-Web Automated instance URL, NOT your OAuth provider's URL!

Important Notes:

  • ⚠️ HTTPS Required: Most OAuth providers require HTTPS for production deployments
  • ⚠️ Exact Match: The callback URI must match exactly (including trailing slashes, if any)
  • ⚠️ Domain: Replace your-cwa-domain.com with your actual CWA domain
  • ⚠️ Port: Include port numbers if not using standard ports (e.g., :8083)
  • πŸ”§ Auto-Configuration: Leave OAuth Redirect Host empty to use automatic detection

Provider-Specific Callback URI Setup:

  • Keycloak: Add to "Valid Redirect URIs" in client configuration
  • Authentik: Add to "Redirect URIs" in provider configuration
  • Google: Add to "Authorized redirect URIs" in Google Cloud Console
  • Azure AD: Add to "Redirect URIs" in app registration

Built-in Test Tools

CWA provides two testing methods:

  1. Metadata URL Test:

    • Validates metadata URL accessibility
    • Checks endpoint discovery
    • Shows available endpoints
  2. OIDC Connection Test:

    • Tests base URL connectivity
    • Validates .well-known/openid-configuration endpoint
    • Verifies endpoint discovery

Common Issues & Solutions

❌ "Unable to fetch OAuth metadata"

Cause: Metadata URL is incorrect or inaccessible Solution:

  • Verify the metadata URL in a browser - it should return JSON
  • Check network connectivity from CWA to the OAuth provider
  • Ensure SSL certificates are valid
  • Try the Metadata URL Test button in the admin panel

❌ "Login failed: User profile incomplete"

Cause: Required JWT fields are missing from the OAuth provider response Solution:

  • Check Username Field and Email Field mappings match your provider's JWT claims
  • Verify OAuth scopes include required claims (e.g., profile, email)
  • Use your provider's token inspector or logs to see available fields
  • Common field names: preferred_username, sub, username, email, mail

❌ "Invalid redirect URI" / "Redirect URI mismatch"

Cause: The callback URI configured in CWA doesn't match what's configured in your OAuth provider, or inconsistent redirect URIs due to changing request context Solution:

  1. Check OAuth Provider Configuration: Ensure redirect URI is: https://your-cwa-domain.com/login/generic/authorized
  2. Verify URL Format: Check for trailing slashes and HTTP vs HTTPS
  3. Include Port Numbers: Use non-standard ports (e.g., :8083) if applicable
  4. Set OAuth Redirect Host: Configure the OAuth Redirect Host setting in Admin β†’ Basic Configuration β†’ OAuth:
    • Use your public CWA URL: https://your-domain.com
    • Required for reverse proxy setups or multiple hostname access
    • Prevents redirect URI changes between sessions
  5. Restart CWA: Changes to OAuth Redirect Host require application restart
  6. Update Provider: The URI must match exactly in both CWA and your OAuth provider

Why this happens: Flask-Dance generates redirect URIs dynamically based on request context. When accessing CWA through different hostnames or after extended periods, the context can change, causing redirect URI mismatches. The OAuth Redirect Host setting forces consistent URI generation.

❌ Users not getting admin privileges

Cause: Group mapping issues or missing group claims Solution:

  • Add groups to OAuth scopes: openid profile email groups
  • Verify Admin Group field matches provider group name exactly (case-sensitive)
  • Check JWT token contains groups claim using your provider's token inspector
  • Ensure users belong to the configured admin group in your OAuth provider

❌ "Login failed, No User Linked With OAuth Account"

Cause: OAuth user exists but isn't linked to a CWA user account Solution:

  • This typically happens when public registration is disabled
  • For existing users: Log in with standard auth, go to Profile, and click "Link to [Provider]" (see Linking Existing Accounts)
  • For new users: Admin users need to manually create accounts for OAuth users first, or enable public registration temporarily
  • Emergency: If you are locked out, you may need to re-enable standard login or public registration via database edits

❌ "Failed to log in with Generic OAuth"

Cause: General OAuth authentication failure Solution:

  • Check CWA logs for detailed error messages
  • Verify OAuth provider is accessible from CWA
  • Test OAuth configuration using the built-in test tools
  • Ensure OAuth client is properly configured in your provider

❌ Users created via OAuth can't log in with passwords

Cause: OAuth users don't have passwords set in CWA Solution:

  • This is expected behavior - OAuth users authenticate via OAuth only
  • If switching to standard authentication, admin must set passwords manually
  • See Authentication Mode Switching section

Debug Mode

Enable debug logging to troubleshoot OAuth issues:

  1. Set log level to Debug in CWA admin panel
  2. Check container logs for detailed OAuth flow information
  3. Look for JWT token contents and endpoint responses

πŸ”’ Security Best Practices

SSL/TLS Requirements

  • Always use HTTPS for production OAuth deployments
  • OAuth providers typically require HTTPS redirect URIs
  • Self-signed certificates may cause issues with some providers

Client Secret Security

  • Store client secrets securely
  • Rotate credentials regularly
  • Use different credentials for development/production

Scope Minimization

  • Request only necessary OAuth scopes
  • Be cautious with administrative scopes
  • Review provider documentation for available scopes

Network Security

  • Restrict OAuth provider access to necessary networks
  • Use firewall rules to control access
  • Monitor OAuth-related logs for suspicious activity

πŸ†˜ Support & Resources

Getting Help

  1. Check Logs: Enable debug logging and check container logs
  2. Test Configuration: Use built-in test tools to validate setup
  3. Community Support: Join our Discord for help
  4. GitHub Issues: Report bugs or request features on GitHub

Useful Resources

Provider Documentation


οΏ½ Authentication Mode Switching

Important Considerations When Switching Authentication Methods

From OAuth to Standard Authentication

⚠️ Critical: Users created via OAuth authentication do not have passwords set in CWA. If you switch from OAuth authentication back to standard username/password authentication, these users will be unable to log in.

Before switching from OAuth to standard authentication:

  1. Identify OAuth-only users: Users created through OAuth will not have passwords
  2. Set passwords for OAuth users: Admin users must manually set passwords for these accounts
  3. Notify affected users: Inform users about the authentication method change

Setting Passwords for OAuth Users

As an admin, you can set passwords for OAuth-created users:

  1. Navigate to Admin Panel β†’ Edit/Add Users
  2. Select the OAuth-created user
  3. Set a new password in the password field
  4. Save the changes

From Standard to OAuth Authentication

This transition is generally smoother:

  • Existing users with passwords can still use them (if not OAuth-only mode)
  • Users can link their OAuth accounts to existing accounts
  • No password data is lost

Best Practices

  1. Plan transitions carefully: Switching authentication methods affects all users
  2. Communicate changes: Inform users before making authentication changes
  3. Test with a small group: Test OAuth configuration with admin users first
  4. Backup user data: Always backup the app.db before making major configuration changes
  5. Document process: Keep records of which users were created via which authentication method

οΏ½πŸ“ Changelog & Updates

Recent Enhancements (v3.1+)

  • βœ… OAuth Redirect Host Setting: Prevents "invalid redirect URI" errors by ensuring consistent callback URLs across sessions and deployment scenarios
  • βœ… OAuth Default Permissions: OAuth users now inherit all default configuration settings (sidebar visibility, locale, language, tags, restrictions) same as manually created users
  • βœ… Auto-Discovery: OIDC metadata URL support for automatic configuration
  • βœ… Manual Override: Checkbox toggle for manual endpoint configuration
  • βœ… Field Mapping: Configurable JWT field extraction
  • βœ… Enhanced Testing: Improved connection testing with detailed feedback
  • βœ… Better UX: Organized UI with collapsible sections
  • βœ… Custom Scopes: Full OAuth scope customization
  • βœ… Group-based Admin Assignment: Automatic admin role based on OAuth groups
  • βœ… Login Branding: Configurable login button text

Future Planned Features

  • πŸ”„ Multiple Providers: Support for configuring multiple OAuth providers simultaneously
  • πŸ”„ Dynamic Login Branding: Login page integration for custom button text
  • πŸ”„ Advanced Group Mapping: Multiple role assignments beyond admin/user (e.g., editor, viewer roles)
  • πŸ”„ Session Management: Enhanced session timeout and refresh token handling
  • πŸ”„ Audit Logging: Detailed OAuth authentication logging

This documentation covers CWA's enhanced OAuth implementation. For additional help, please visit our Discord community or check the GitHub repository.

Clone this wiki locally