Upgrading to 1.0
Version 1.0 hardens the security defaults and stabilizes the public API. Most applications only need to check the points below and update a few lines of configuration.
npm i @maximemrf/adonisjs-jwt@^1.0.0@adonisjs/auth is now a peer dependency. It is already installed if you use the guard.
Breaking changes
Signing key derived from the application key
Without secret, tokens were signed with the raw application key. They are now signed with a key derived from it, see Security.
- Access tokens issued by 0.9 are rejected after the upgrade. Clients get a
401and must refresh their token or log in again. Refresh tokens are stored in the database and stay valid, so clients with a refresh token don't have to log in again. - The application key must be at least 32 characters, otherwise the guard throws at startup. AdonisJS generates 32 characters keys by default.
Applications that set secret keep their tokens, as long as the secret is at least 32 characters. A shorter secret now stops the app from booting: replace it with a longer one (all tokens are then rejected), see Security.
No database migration is needed: the jwt_refresh_tokens table of 0.9 works as is.
Access tokens expire after 1 hour by default
Without tokenExpiresIn, access tokens never expired. They now expire after 1h. Set tokenExpiresIn to keep another lifetime.
A content function that sets exp itself no longer compiles, and throws when issuing a token: remove exp and use tokenExpiresIn. The same goes for iss and aud when issuer and audience are configured.
JWKS requires issuer and audience
In JWKS mode, the guard throws at startup if issuer is missing, or if neither audience nor verifyPayload is set. Set them to the values of your identity provider, see JWKS. If your provider's tokens have no aud claim specific to your API (Amazon Cognito access tokens, for example), check the claim that identifies your API with verifyPayload instead of audience.
The configuration is checked when the app boots
The guard options are checked when config/auth.ts is loaded, so a wrong configuration stops the app from booting with an explicit error, instead of failing on every request:
tokenExpiresInandrefreshTokenExpiresInmust be a positive number of seconds, or a duration of at least 1 second with a unit ('15m','7d'). A string without unit, such as'3600'read from an env variable, is rejected: validate the variable as a number instart/env.ts, or add a unit.clockTolerancemust not be negative.secretand the application key must be at least 32 characters.- With asymmetric keys,
publicKeymust belong to the same key pair asprivateKey. - With
jwks,jwks.jwksUriis required.
Ace commands that boot the application, such as node ace migration:run, fail too: fix the configuration before deploying.
revoke() fails when nothing is revoked
revoke() used to succeed silently when the request had no valid refresh token. It now throws E_UNAUTHORIZED_ACCESS (a 401) after clearing the cookies. A client that sends its access token instead of its refresh token on logout now learns that its refresh token was not revoked, see Revoke a refresh token.
Your logout route needs no change: an API client gets the 401. If logging out must always succeed, for example on a page, ignore the error, the cookies are cleared anyway:
import { errors } from '@adonisjs/auth'
router.post('logout', async ({ auth, response }) => {
try {
await auth.use('jwt').revoke()
} catch (error) {
// only "nothing to revoke": a database outage must still fail the request
if (!(error instanceof errors.E_UNAUTHORIZED_ACCESS)) throw error
}
return response.redirect('/login')
})Clients that keep the tokens in memory must send the refresh token on logout, in the body or the Authorization header, see Single-page apps.
401 responses follow the Accept header
401 responses were always plain text. JSON requests now get a JSON body, and page or Inertia requests are redirected to the login route of the auth middleware, see Authentication. If your exception handler already formats these errors, it keeps precedence.
Refresh token in the query string
A refresh token sent in the query string (?refreshToken=…) is ignored. Send it in the request body, a cookie or the Authorization header.
Refresh token body field follows refreshTokenName
The refresh token was always read from the refreshToken body field. It is now read from the field named after refreshTokenName. If you set a custom refreshTokenName and your clients send the token in a refreshToken field, rename the field in your clients.
Token lookup order
- Refresh token: when
useCookiesForRefreshTokenis enabled, the cookie is read before the request body. - Access token: the
Authorizationheader is read before the cookie, and the cookie is only read whenuseCookiesis enabled. If you set thetokencookie yourself withoutuseCookies, enableuseCookies.
See Cookies and token transport.
Lifetimes in the generate() result are in seconds
expiresIn and refreshTokenExpiresIn, returned by generate() and generateWithRefreshToken(), are now a number of seconds. They used to repeat the config value as is, so '1h' by default.
"expiresIn": "1h",
"expiresIn": 3600, If a client reads these fields (to schedule a refresh, or to compute an expiration date), update it to read a number of seconds. Clients that ignore them are not affected.
Refresh tokens expire after 7 days by default
Without refreshTokenExpiresIn, refresh tokens used to never expire. They now expire after 7 days. Set refreshTokenExpiresIn to keep a longer lifetime. Refresh tokens issued before the upgrade have no expiration in the database and stay valid until they are used. To make them expire too, delete them, or set their expires_at column.
Public types
These changes only affect TypeScript code that uses the types of the package:
Custom user providers must declare the type of the user they return, like the providers of
@adonisjs/authdo:tsexport class ServiceUserProvider implements JwtUserProviderContract<Service> { declare [symbols.PROVIDER_REAL_USER]: Servicecontentmust returnuserIdunlessgetUserIdis set, since the guard reads the user id from this claim. WithgetUserId,contentcan use another claim, such assub.@maximemrf/adonisjs-jwt/typesonly exports types. ImportDEFAULT_TOKEN_EXPIRES_INfrom the main entrypoint.JwtGuardOptionshas nodriveroption. Custom drivers were never supported.The type of the
jwtGuard()config is exported asJwtGuardConfig.
Other changes
These changes don't require any action.
Imports: import from the main entrypoint. The old path still works.
tsimport { jwtGuard } from '@maximemrf/adonisjs-jwt/jwt_config' import { jwtGuard } from '@maximemrf/adonisjs-jwt'Typed
content:user.getOriginal()is typed after your model, the generic signature and the cast are no longer needed.tscontent: <T>(user: JwtGuardUser<T>) => ({ email: (user.getOriginal() as User).email, content: (user) => ({ email: user.getOriginal().email, userId: user.getId(), }),Then remove the imports that are no longer used, such as
JwtGuardUserand the model imported for the cast, otherwisetscreports them withnoUnusedLocals.AdonisJS v7 apps without
secret: the guard now readsAPP_KEYfrom the environment whenconfig/app.tshas noappKey, which is the case of new AdonisJS v7 apps. If you addedexport const appKey = env.get('APP_KEY')toconfig/app.tsfor 0.9, you can remove it: both give the same signing key, and tokens stay valid.JwtGuardis exported from the package entrypoint, for guards built withoutjwtGuard(). Its lifetime option istokenExpiresIn, like injwtGuard().node ace configurenow adds the guard toconfig/auth.tsand therefreshTokensprovider to the user model, see Installation.JWKS defaults: key fetches are cached and rate limited by default, see Key fetching.
revoke()also clears the access and refresh token cookies.refreshTokenAbilitiesare now checked bygenerateWithRefreshToken().user.currentTokenholds the new access token aftergenerateWithRefreshToken(), which no longer returnsundefinedin its type.Concurrent refreshes: when two requests use the same refresh token, the one that fails no longer leaves the guard authenticated.