Authentication with JWT
@navios/jwt signs and verifies JSON Web Tokens in an injectable service. This page builds bearer-token authentication with it from start to finish: a login endpoint signs a token, a guard verifies it and stores the user for the request, and an attribute marks the routes that need no token.
Configure the service
provideJwtService returns an injection token with a configured service behind it. Create it once and export it; every inject() of it gives the same JwtService instance.
The algorithms a token may use follow from the key: a secret verifies only HMAC, a public key only the algorithms of its type. List algorithms in verifyOptions to narrow them further. A time span is a number of seconds or a string with a unit ('15m'); '900' is refused.
The audience ties a token to one purpose. An application that also issues refresh tokens has a second service with an audience of its own; without it, a refresh token signed with the same key would pass as an access token:
Every call of provideJwtService is a service of its own; name is what error messages call it.
When the configuration comes from another service, pass a function. It receives a factory context, may be asynchronous, and runs once, the first time the service is resolved:
The configuration is checked when the service is first resolved, which for a service injected into a guard is when the application starts. A key that is empty, undefined or cannot be parsed, or an option without a value, rejects with a DIError whose code is InitializationError and whose message names the key. So a missing environment variable stops the start instead of turning every request into a 401. A secret shorter than 32 bytes is a warning, once per process. To configure no key at all, leave the properties out.
Asymmetric keys
With an RSA or ECDSA key pair the private key signs and the public key verifies, so services that only verify need only the public key:
A string, Buffer or Uint8Array is a PEM. For another encoding pass a KeyObject: createPublicKey({ key, format: 'der', type: 'spki' }) or createPublicKey({ key: jwk, format: 'jwk' }) from node:crypto. A PEM in an environment variable often contains the two characters \n instead of line breaks and is refused; replace them with value.replaceAll('\\n', '\n'). An encrypted private key is { key, passphrase }. EdDSA keys are not supported.
Choosing the key per token
keys picks the key for each call, for example by the kid header of the token when keys are rotated, or per tenant. It is called with { use: 'verify', header }, the parsed header of the token, or with { use: 'sign', payload }.
undefined, also as thekeyof{ key, algorithms }, means that there is no such key: the token is rejected with aJsonWebTokenError. When signing it is an error of the application.- A token whose
kidfinds something else that is not a key (constructorin a plain object), or a key no supported algorithm works with (an Ed25519 key in a JWKS), is rejected too. An empty string or empty bytes are an error of the application. - The header comes from the sender and is not verified yet. A malformed token, or one with an algorithm that is not accepted, is rejected before
keysis called. - Return a
KeyObjectmade once, as above, so that the key is not parsed for every request. Text or bytes do not say whether they are a secret or a key pair; they need{ key, algorithms }or pinnedalgorithms(algorithmwhen signing). - With
{ key, keyid, algorithms }thekeyidbecomes thekidheader of the signed token, andalgorithmslimits what the key is used for. - The function may return a promise, for example for a JWKS lookup. It is awaited by
signAsync()andverifyAsync();sign()andverify()throw, because they cannot wait for the key.
Call provideJwtService once per service, at module level. A service made for each tenant or each key would stay in the container until it is disposed; use keys, or pass the key to the call.
Sign a token at login
The login endpoint is new, so it gets a declaration. A failed login is a declared 401.
The handler checks the credentials and signs a payload. PasswordsService stands for however your application verifies a password; its check resolves to { id, roles } or null. Public is defined with the guard in the next section.
sign adds iat and, because of expiresIn, exp to the payload. Keep the payload small and free of secrets: anyone holding the token can read it.
Verify in a guard
The guard needs two small definitions. CurrentUser is a context key, a typed per-request slot. Public is a flag attribute for routes that skip the check.
- The guard throws
UnauthorizedExceptioninstead of returningfalse, becausefalseanswers 403. See Guards and interceptors. - A 401 carries a
www-authenticateheader, which HTTP requires and clients use. Headers set onctx.replyare sent with the error response. The scheme name is case-insensitive, hence theiflag. - An error that is not a
JsonWebTokenErroris passed on and answers 500: the configuration or the key lookup failed, not the token. verify<T>does not validate the payload's shape; the type argument is a cast. The signature and theaudienceguarantee that your server issued the payload as an access token, so the cast is as reliable as yoursigncalls for this kind of token.verifyis synchronous, so the guard adds no promise to the request. UseverifyAsyncwhenkeysreturns a promise.
Attach the guard
Put the guard on the root module. It then runs for every route of the application, and @Public() opts a handler, a controller or a whole module out.
Guards run before the request body is read, so a request without a valid token is rejected with 401 whatever its body contains.
Read the user in a handler
Behind the guard, ctx.get(CurrentUser) is the user the guard stored.
On a @Public() route the key is not set and ctx.get throws; use ctx.find(CurrentUser) there. Checking roles per route is the example on the Attributes page.
The service
inject(Jwt) is a JwtService:
Per-call options are merged over the configured signOptions or verifyOptions. An option that is undefined is not given, so it never switches off a configured check; an empty one is an error. When signing, null leaves out a default claim (expiresIn: null is a token without exp), and a default is not applied to a claim the payload already has.
A call may carry its own secret, privateKey or publicKey, which wins over everything configured. A key that is passed but undefined or empty is an error; it does not fall back to the key of the service.
verify, verifyAsync and decode take complete: true to return { header, payload, signature }. A verified payload is always an object; a token with another payload is rejected.
Errors
verify and verifyAsync throw one of these for a token that cannot be accepted, whatever is wrong with it:
The first two extend JsonWebTokenError, so test for them first. A missing key or a wrong option is a plain Error, so it is not answered as a wrong token. None of them is an HttpException: one that escapes a guard or a handler is an unexpected error and answers 500. Either translate them where you verify, as the guard above does, or map the base class once for the whole application:
app.mapError is described in Errors.
Types
Replacing the service
Each token provideJwtService returns can be bound to another implementation, for example a fake in a test. The other services are not affected:
The same entry works in @Module({ providers }), and bind(Jwt) of a TestContainer does the same. Providers describes the mechanism.
Testing protected routes
In a test, resolve the same service from the application and sign a token for the user you need:
Creating app and the test client is covered in Testing.