Basic auth guard

Basic authentication

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.

If you decide to not use the mixin, then make sure to implement a static verifyCredentials method with the following signature.

export default class User extends BaseModel {
/**
* Dummy implementation: it is recommended to use
* the AuthFinder mixin
*/
static verifyCredentials(uid: string, password: string) {
const user = await this.query().where('email', uid).first()
if (!user) {
throw new Error('Invalid user credentials')
}
const isValid = await hash.verify(user.password, password)
if (!isValid) {
throw new Error('Invalid user credentials')
}
return user
}
}

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']
}))