AdonisJS Auth
repository·10.x·Indexed 42 days ago
https://github.com/adonisjs/authThe 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.
What's inside AdonisJS Auth
- @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.
Access the @adonisjs/auth official documentation
10.xFor detailed guides, installation instructions, configuration details, and API references, please refer to the official AdonisJS documentation website.
https://docs.adonisjs.com/guides/authentication/introductionAugment Authenticators for type safety
10.xTo ensure
AuthServiceknows about your configured guards, you must augment theAuthenticatorsinterface. This is typically done in a declaration file after defining your auth configuration.declare module '@adonisjs/auth/types' { interface Authenticators { web: SessionGuardFactory api: TokenGuardFactory } }Use the Authenticator to manage authentication
10.xThe
Authenticatorclass 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()orauthenticateUsing()to verify a user. - Checking status: Using
check()orcheckUsing()to silently verify if a user is logged in. - Accessing user data: Retrieving the currently authenticated user via the
userproperty orgetUserOrFail()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') }- Authenticating requests: Using
Use InitializeAuthMiddleware to add auth to the HTTP context
10.xThe
InitializeAuthMiddlewareis responsible for creating a request-specificAuthenticatorinstance for every HTTP request. It attaches theauthobject to theHttpContext, 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
authmiddleware instead.When registered, this middleware:
- Adds
ctx.authto theHttpContext. - Shares the
authinstance with the Edge template engine (ifctx.viewis present) so you can check authentication status directly in your templates.
// Registering the middleware in your router router.use([() => import('#middleware/initialize_auth_middleware')])- Adds
Configure the auth package with defineConfig
10.xUse the
defineConfigfunction to set up the authentication configuration for your AdonisJS application. This function allows you to specify adefaultguard and a map of availableguards.Each guard in the
guardsobject can be aGuardFactory(a function that returns a guard) or aGuardConfigProvider(an object that resolves to a guard, often used for asynchronous loading or dependency injection). ThedefineConfigfunction 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') }) }) } })Install the Japa auth browser client plugin
10.xWhen writing browser-based authentication tests using Japa and Playwright, you can use the
authBrowserClientplugin 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
authBrowserClientand add it to your Japa configuration plugins array, passing the AdonisJSappservice instance.import { authBrowserClient } from '@adonisjs/auth/plugins/japa/browser_client' export const plugins: PluginFn[] = [ authBrowserClient(app) ]Setup the Auth API Client for Japa testing
10.xWhen writing integration tests for API-based authentication using the Japa test runner, you can use the
authApiClientplugin. This plugin extends the JapaApiClientto allow you to easily simulate authenticated requests by callingloginAsorwithGuardon 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) ]Use the `withAuthFinder` mixin to add authentication to Lucid models
10.xThe
withAuthFindermixin adds essential authentication methods and lifecycle hooks to your Lucid models. It automates password hashing via a@beforeSavehook 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
withAuthFinderwhen extending yourBaseModel.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 }Configure PostgreSQL for local development
10.xThe
docker-compose.ymlfile provides a PostgreSQL 11 service. Configuration is driven by the following environment variables from your.envfile: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:5432Configure MSSQL for local development
10.xThe
docker-compose.ymlfile provides a Microsoft SQL Server 2019 service. Configuration is driven by the following environment variables from your.envfile:MSSQL_PASSWORD: The password for theSA(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:1433Configure MySQL for local development
10.xThe
docker-compose.ymlfile 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 tomysql_native_password.Configuration is driven by the following environment variables from your
.envfile: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