Setting up authentication for both web and API routes using AdonisJS can be achieved by utilizing its built-in authentication system and the @adonisjs/auth
package. Here’s a step-by-step guide to configure it for admin auth and user auth on the web, and user auth for the API.
Step 1: Install the Auth Package
If the @adonisjs/auth
package is not installed, install it using:
npm install @adonisjs/auth
Step 2: Configure the Auth Package
Run the configuration command to set up the auth system:
node ace configure @adonisjs/auth
- Choose Lucid Database for managing users.
- Select API Tokens for API authentication.
This will create the auth.ts
file in the config
directory and add a migration file for tokens.
Step 3: Run Migrations
Run the migrations to set up the users
table and the api_tokens
table.
node ace migration:run
Step 4: Update the users
Table
Add roles (admin
, user
, etc.) to the users
table. Update the migration file if necessary:
table.string('role').defaultTo('user') // Add a role column
node ace migration:run
Step 5: Set Up Auth Guards in config/auth.ts
Define guards for web and api authentication.
import { AuthConfig } from '@ioc:Adonis/Addons/Auth'
const authConfig: AuthConfig = {
guard: 'web', // Default guard
list: {
web: {
driver: 'session', // For web authentication
provider: {
driver: 'lucid',
model: () => import('App/Models/User'),
identifierKey: 'email', // Identify users via email
},
},
api: {
driver: 'oat', // For API authentication
provider: {
driver: 'lucid',
model: () => import('App/Models/User'),
identifierKey: 'email',
},
},
},
}
Step 6: Create Middleware for Role-Based Access
Create middleware to differentiate between admin
and user
roles.
Run the middleware creation command:
app/Middleware/RoleMiddleware.ts
):import { HttpContextContract } from '@ioc:Adonis/Core/HttpContext'export default class RoleMiddleware {public async handle({ auth, response }: HttpContextContract, next: () => Promise<void>, roles: string[]) {const user = auth.userif (!user || !roles.includes(user.role)) {return response.unauthorized('Access denied')}await next()}}
start/kernel.ts
:Server.middleware.registerNamed({role: 'App/Middleware/RoleMiddleware',})
Step 7: Define Routes
Update start/routes.ts
for web and API routes.
Web Routes
Route.group(() => {Route.get('/admin', 'AdminController.index').middleware(['auth:web', 'role:admin'])Route.get('/user', 'UserController.index').middleware(['auth:web', 'role:user'])}).prefix('web')
Route.group(() => {Route.get('/profile', 'Api/UserController.profile').middleware(['auth:api'])Route.post('/login', 'Api/AuthController.login')Route.post('/register', 'Api/AuthController.register')}).prefix('api')
Step 8: Create Controllers
Admin and User Controllers for Web
Generate controllers for admin and user:
node ace make:controller AdminController
node ace make:controller UserController
Update the controllers:
AdminController.ts
export default class AdminController {
public async index({ auth }) {
return `Welcome Admin ${auth.user!.email}`
}
}
UserController.ts
export default class UserController {
public async index({ auth }) {
return `Welcome User ${auth.user!.email}`
}
}
API Auth and User Controllers
Generate controllers for API:
node ace make:controller Api/AuthController
node ace make:controller Api/UserController
import User from 'App/Models/User'export default class AuthController {public async login({ request, auth }) {const { email, password } = request.only(['email', 'password'])const token = await auth.use('api').attempt(email, password)return token}public async register({ request }) {const userData = request.only(['email', 'password', 'role'])const user = await User.create(userData)return user}}
export default class UserController {public async profile({ auth }) {return auth.user}}
Step 9: Test Your Setup
Web:
- Visit
/web/admin
or/web/user
to test role-based authentication.
- Visit
API:
- Use tools like Postman to test
/api/register
and/api/login
. - Add the token from login as a Bearer token in the header to access
/api/profile
.
Key Features of AdonisJS Auth
- Multiple Guards: Supports both session-based and token-based authentication.
- Lucid ORM Integration: Works seamlessly with the database.
- Role-Based Middleware: Control access based on user roles.
- API Token Management: Secure your APIs with OAuth 2.0-compatible tokens.
Requirements
Before you begin, ensure you have:
- Node.js v14+ installed.
- AdonisJS v5+ installed via the AdonisJS CLI.
- A database (e.g., MySQL, PostgreSQL) configured with AdonisJS.