AdonisJS Auth

repository·10.x·Indexed 42 days ago

https://github.com/adonisjs/auth

The official authentication provider for the AdonisJS framework, version 10.1.0. It provides a robust system for managing secure authentication flows using various strategies and guards, including SessionGuard, BasicAuthGuard, and AccessTokensGuard. The package includes support for Lucid models via the withAuthFinder mixin and provides specialized user providers and token management for database-backed authentication.

Tokens
11.4K
Snippets
53
Records
61
Agent score
53%

What's inside AdonisJS Auth

  1. Introduction to @adonisjs/auth

    10.x
    @adonisjs/auth is the official authentication package for the AdonisJS framework. It provides a robust system for managing user authentication, supporting various authentication strategies and drivers.
  2. Access the @adonisjs/auth official documentation

    10.x

    For detailed guides, installation instructions, configuration details, and API references, please refer to the official AdonisJS documentation website.

    https://docs.adonisjs.com/guides/authentication/introduction
  3. Augment Authenticators for type safety

    10.x

    To ensure AuthService knows about your configured guards, you must augment the Authenticators interface. This is typically done in a declaration file after defining your auth configuration.

    declare module '@adonisjs/auth/types' {
      interface Authenticators {
        web: SessionGuardFactory
        api: TokenGuardFactory
      }
    }
  4. Use the Authenticator to manage authentication

    10.x

    The Authenticator class is the primary entry point for performing authentication operations in an AdonisJS request. It manages multiple guards (e.g., session, api) and tracks the authentication state for the current HTTP request.

    Key capabilities include:

    • Authenticating requests: Using authenticate() or authenticateUsing() to verify a user.
    • Checking status: Using check() or checkUsing() to silently verify if a user is logged in.
    • Accessing user data: Retrieving the currently authenticated user via the user property or getUserOrFail() method.
    • Switching guards: Using use(guardName) to interact with a specific guard instance.
    // Example of basic authentication flow
    const user = await auth.authenticate()
    console.log(user.email)
    
    // Example of checking authentication without throwing
    if (await auth.check()) {
      console.log('User is authenticated')
    }
  5. Use InitializeAuthMiddleware to add auth to the HTTP context

    10.x

    The InitializeAuthMiddleware is responsible for creating a request-specific Authenticator instance for every HTTP request. It attaches the auth object to the HttpContext, making it available throughout your application's request lifecycle.

    Important: This middleware does not protect routes from unauthenticated users. It only initializes the authentication mechanism. To protect routes, you must use the auth middleware instead.

    When registered, this middleware:

    1. Adds ctx.auth to the HttpContext.
    2. Shares the auth instance with the Edge template engine (if ctx.view is present) so you can check authentication status directly in your templates.
    // Registering the middleware in your router
    router.use([() => import('#middleware/initialize_auth_middleware')])
  6. Configure the auth package with defineConfig

    10.x

    Use the defineConfig function to set up the authentication configuration for your AdonisJS application. This function allows you to specify a default guard and a map of available guards.

    Each guard in the guards object can be a GuardFactory (a function that returns a guard) or a GuardConfigProvider (an object that resolves to a guard, often used for asynchronous loading or dependency injection). The defineConfig function ensures that all guards are properly resolved before being passed to the auth service.

    import { defineConfig } from '@adonisjs/auth'
    import { sessionGuard, sessionUserProvider } from '@adonisjs/auth/session'
    
    const authConfig = defineConfig({
      default: 'web',
      guards: {
        web: sessionGuard({
          useRememberMeTokens: false,
          provider: sessionUserProvider({
            model: () => import('#models/user')
          })
        })
      }
    })
  7. Install the Japa auth browser client plugin

    10.x

    When writing browser-based authentication tests using Japa and Playwright, you can use the authBrowserClient plugin to easily authenticate users within your browser context. This allows you to perform page visits as a logged-in user by automatically setting the necessary cookies or session data.

    To use it, import authBrowserClient and add it to your Japa configuration plugins array, passing the AdonisJS app service instance.

    import { authBrowserClient } from '@adonisjs/auth/plugins/japa/browser_client'
    
    export const plugins: PluginFn[] = [
      authBrowserClient(app)
    ]
  8. Setup the Auth API Client for Japa testing

    10.x

    When writing integration tests for API-based authentication using the Japa test runner, you can use the authApiClient plugin. This plugin extends the Japa ApiClient to allow you to easily simulate authenticated requests by calling loginAs or withGuard on your API requests. This automatically handles the underlying authentication logic (like setting headers, sessions, or cookies) for the test request.

    import { authApiClient } from '@adonisjs/auth/plugins/japa/api_client'
    
    export const plugins: PluginFn[] = [
      authApiClient(app)
    ]
  9. Use the `withAuthFinder` mixin to add authentication to Lucid models

    10.x

    The withAuthFinder mixin adds essential authentication methods and lifecycle hooks to your Lucid models. It automates password hashing via a @beforeSave hook and provides methods for finding users and verifying credentials.

    To use it, pass your hash manager (or a function that returns a hash instance) and an optional configuration object to withAuthFinder when extending your BaseModel.

    Configuration Options:

    • uids: An array of column names to search for the user (e.g., ['email', 'username']). Defaults to ['email'].
    • passwordColumnName: The name of the column storing the password hash. Defaults to 'password'.
    import { BaseModel } from '@adonisjs/lucid/orm'
    import { withAuthFinder } from '@adonisjs/auth/mixins/lucid'
    import hash from '@adonisjs/core/services/hash'
    
    class User extends withAuthFinder(hash, {
      uids: ['email', 'username'],
      passwordColumnName: 'password'
    })(BaseModel) {
      // User model implementation
    }
  10. Configure PostgreSQL for local development

    10.x

    The docker-compose.yml file provides a PostgreSQL 11 service. Configuration is driven by the following environment variables from your .env file:

    • PG_DATABASE: The name of the database to create.
    • PG_USER: The username for the database.
    • PG_PASSWORD: The password for the user.
    • PG_PORT: The host port to map to the container's 5432 port.
    services:
      pg:
        image: postgres:11
        environment:
          - POSTGRES_DB=$PG_DATABASE
          - POSTGRES_USER=$PG_USER
          - POSTGRES_PASSWORD=$PG_PASSWORD
        ports:
          - $PG_PORT:5432
  11. Configure MSSQL for local development

    10.x

    The docker-compose.yml file provides a Microsoft SQL Server 2019 service. Configuration is driven by the following environment variables from your .env file:

    • MSSQL_PASSWORD: The password for the SA (System Administrator) user.
    • MSSQL_PORT: The host port to map to the container's 1433 port.

    Note: The service automatically sets ACCEPT_EULA='Y' to accept the End User License Agreement.

    services:
      mssql:
        image: mcr.microsoft.com/mssql/server:2019-latest
        environment:
          - SA_PASSWORD=$MSSQL_PASSWORD
          - ACCEPT_EULA='Y'
        ports:
          - $MSSQL_PORT:1433
  12. Configure MySQL for local development

    10.x

    The docker-compose.yml file provides a pre-configured MySQL 8.0 service. It uses specific command flags to optimize for development speed (disabling certain sync and flush operations) and sets the authentication plugin to mysql_native_password.

    Configuration is driven by the following environment variables from your .env file:

    • MYSQL_USER: The username for the database.
    • MYSQL_PASSWORD: The password for the user and the root user.
    • MYSQL_DATABASE: The name of the database to create.
    • MYSQL_PORT: The host port to map to the container's 3306 port.
    services:
      mysql:
        image: mysql:8.0
        command: --default-authentication-plugin=mysql_native_password --sync_binlog=0 --innodb_doublewrite=OFF  --innodb-flush-log-at-trx-commit=0 --innodb-flush-method=nosync
        environment:
          - MYSQL_USER=$MYSQL_USER
          - MYSQL_PASSWORD=$MYSQL_PASSWORD
          - MYSQL_DATABASE=$MYSQL_DATABASE
          - MYSQL_ROOT_PASSWORD=$MYSQL_PASSWORD
        ports:
          - $MYSQL_PORT:3306