Authentication
Issue a token
Verify the user's credentials, then call generate():
// start/routes.ts
import router from '@adonisjs/core/services/router'
import User from '#models/user'
router.post('login', async ({ request, auth }) => {
const { email, password } = request.only(['email', 'password'])
const user = await User.verifyCredentials(email, password)
return await auth.use('jwt').generate(user)
})generate() returns:
{
"type": "bearer",
"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
"expiresIn": 3600,
"refreshToken": "rt_MQ.xxxxxxxx",
"refreshTokenExpiresIn": 604800
}expiresIn and refreshTokenExpiresIn are lifetimes in seconds, like expires_in in OAuth 2.0, whatever the format of the config ('1h' gives 3600). A client can use them to refresh the access token before it expires. refreshToken and refreshTokenExpiresIn are only set when refresh tokens are configured. With cookies enabled, generate() also sets the tokens as cookies on the response.
TIP
User.verifyCredentials comes from the withAuthFinder mixin of @adonisjs/auth. See Verifying user credentials.
Protect routes
Use the auth middleware. If jwt is the default guard:
import { middleware } from '#start/kernel'
router
.get('me', async ({ auth }) => {
return auth.getUserOrFail()
})
.use(middleware.auth())Otherwise, name the guard:
router
.get('me', async ({ auth }) => {
return auth.use('jwt').getUserOrFail()
})
.use(middleware.auth({ guards: ['jwt'] }))The client sends the token in the Authorization header:
GET /me HTTP/1.1
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...A missing, expired or invalid token is rejected with an E_UNAUTHORIZED_ACCESS error, which AdonisJS turns into a 401 response. The response follows the Accept header of the request, like the built-in access_tokens guard:
- JSON requests get
{ "errors": [{ "message": "Unauthorized access" }] }. - JSON:API requests get
{ "errors": [{ "code": "E_UNAUTHORIZED_ACCESS", "title": "Unauthorized access" }] }. - HTML requests, such as page loads and Inertia visits, are redirected to the login route when the
authmiddleware has one (loginRoute, set by the web and Inertia starter kits). Otherwise they get a plain text401.
Optional authentication
To know whether a request is authenticated without rejecting it, use check():
router.get('posts', async ({ auth }) => {
if (await auth.use('jwt').check()) {
// auth.use('jwt').user is set
}
})Current token
After authenticate(), the access token of the request is available as user.currentToken, like user.currentAccessToken with the AdonisJS access tokens guard:
const user = auth.use('jwt').getUserOrFail()
user.currentToken // the JWT sent by the clientAfter generateWithRefreshToken(), it holds the new access token.
Log out
Access tokens are stateless: they stay valid until they expire. Logging out revokes the refresh token and clears the cookies set by the guard, see Revoking tokens. The client must send its refresh token, not only its access token, see Single-page apps and Inertia.