Basic auth guard

Basic authentication guard

The basic auth guard is an implementation of the HTTP authentication framework, in which the client must pass the user credentials as a base64 encoded string via the Authorization header. The server allows the request if the credentials are valid. Otherwise, a web-native prompt is displayed to re-enter the credentials.

Configuring the guard

The authentication guards are defined inside the config/auth.ts file. You can configure multiple guards inside this file under the guards object.

import { defineConfig } from '@adonisjs/auth'
import { basicAuthGuard, basicAuthUserProvider } from '@adonisjs/auth/basic_auth'
const authConfig = defineConfig({
default: 'basicAuth',
guards: {
basicAuth: basicAuthGuard({
provider: basicAuthUserProvider({
model: () => import('#models/user'),
}),
})
},
})
export default authConfig

The basicAuthGuard method creates an instance of the BasicAuthGuard class. It accepts a user provider that can be used to find users during authentication.

The basicAuthUserProvider method creates an instance of the BasicAuthLucidUserProvider class. It accepts a reference to the model to use for verifying user credentials.

Preparing the User model

The model (User model in this example) configured with the basicAuthUserProvider must use the AuthFinder mixin to verify the user credentials during authentication.

import { DateTime } from 'luxon'
import { compose } from '@adonisjs/core/helpers'
import { BaseModel, column } from '@adonisjs/lucid/orm'
import hash from '@adonisjs/core/services/hash'
import { withAuthFinder } from '@adonisjs/auth/mixins/lucid'
const AuthFinder = withAuthFinder(() => hash.use('scrypt'), {
uids: ['email'],
passwordColumnName: 'password',
})
export default class User extends compose(BaseModel, AuthFinder) {
@column({ isPrimary: true })
declare id: number
@column()
declare fullName: string | null
@column()
declare email: string
@column()
declare password: string
@column.dateTime({ autoCreate: true })
declare createdAt: DateTime
@column.dateTime({ autoCreate: true, autoUpdate: true })
declare updatedAt: DateTime
}

Protecting routes

Once you have configured the guard, you can use the auth middleware to protect routes from unauthenticated requests. The middleware is registered inside the start/kernel.ts file under the named middleware collection.

import router from '@adonisjs/core/services/router'
export const middleware = router.named({
auth: () => import('#middleware/auth_middleware')
})
import { middleware } from '#start/kernel'
import router from '@adonisjs/core/services/router'
router
.get('dashboard', ({ auth }) => {
return auth.user
})
.use(middleware.auth({
guards: ['basicAuth']
}))

Handling authentication exception

The auth middleware throws the E_UNAUTHORIZED_ACCESS if the user is not authenticated. The exception is automatically converted to an HTTP response with the WWW-Authenticate header in the response. The WWW-Authenticate challenges the authentication and triggers a web-native prompt to re-enter the credentials.

Getting access to the authenticated user

You may access the logged-in user instance using the auth.user property. Since, you are using the auth middleware, the auth.user property will always be available.

import { middleware } from '#start/kernel'
import router from '@adonisjs/core/services/router'
router
.get('dashboard', ({ auth }) => {
return `You are authenticated as ${auth.user!.email}`
})
.use(middleware.auth({
guards: ['basicAuth']
}))

Get authenticated user or fail

If you do not like using the non-null assertion operator on the auth.user property, you may use the auth.getUserOrFail method. This method will return the user object or throw E_UNAUTHORIZED_ACCESS exception.

import { middleware } from '#start/kernel'
import router from '@adonisjs/core/services/router'
router
.get('dashboard', ({ auth }) => {
const user = auth.getUserOrFail()
return `You are authenticated as ${user.email}`
})
.use(middleware.auth({
guards: ['basicAuth']
}))