Packages / Auth / JWT Provider

JWT Provider

A 15-line Injectable class that authenticates Bearer tokens with JwtService and loads the user.

Problem

You want every protected route to have a fully populated ctx.user, derived from a JWT in the Authorization: Bearer <token> header. If the token is missing, expired, or invalid, the request should be rejected with 401.

Solution

A single @Injectable() provider that combines JwtService with the fromHeader extractor.

typescript
// src/auth/providers/jwt-auth.provider.ts
import { Injectable, inject, UnauthorizedException, type RequestContext } from '@miiajs/core'
import { fromHeader, type AuthProvider } from '@miiajs/auth'
import { JwtService, type JwtPayload } from '@miiajs/jwt'
import { UsersService } from '../../users/users.service.js'

@Injectable()
export class JwtAuth implements AuthProvider {
  private jwtService = inject(JwtService)
  private usersService = inject(UsersService)
  private extract = fromHeader()

  async authenticate(ctx: RequestContext) {
    const token = this.extract(ctx)
    if (!token) throw new UnauthorizedException('Missing token')

    let payload: JwtPayload
    try {
      payload = await this.jwtService.verify(token)
    } catch {
      throw new UnauthorizedException('Invalid token')
    }

    const user = await this.usersService.findById(payload.sub as number)
    if (!user) throw new UnauthorizedException('User no longer exists')
    return user
  }
}

That's it. Fifteen lines of logic, fully typed, fully injectable.

Wire it up

Register the provider in your auth module. The guard is checked from the module of every controller that uses it, so make the module global and export the provider:

typescript
// src/auth/auth.module.ts
import { Module } from '@miiajs/core'
import { UsersModule } from '../users/users.module.js'
import { JwtAuth } from './providers/jwt-auth.provider.js'

@Module({
  global: true,
  imports: [UsersModule], // UsersService, exported by UsersModule
  providers: [JwtAuth],
  exports: [JwtAuth],
})
export class AuthModule {}

JwtService comes from JwtModule.configure(options, { global: true }) in the root module. Without global on AuthModule, every module whose controllers use AuthGuard(JwtAuth) would have to import it - and for UsersModule, which AuthModule imports, that import would close a cycle.

Apply the guard to any controller or route:

typescript
// src/users/users.controller.ts
import { Controller, Get, UseGuard, type RequestContext } from '@miiajs/core'
import { AuthGuard } from '@miiajs/auth'
import { JwtAuth } from '../auth/providers/jwt-auth.provider.js'

@Controller('/users')
@UseGuard(AuthGuard(JwtAuth))
export class UsersController {
  @Get('/me')
  me(ctx: RequestContext) {
    return ctx.user
  }
}

Declaring ctx.user

@miiajs/core intentionally does not pre-declare user on RequestContext - the package has no opinion on what an authenticated subject looks like. Before you can touch ctx.user anywhere, augment the interface once in your project with the type your provider returns:

typescript
// src/types/core.d.ts
import type { User } from '../users/user.table.js'

declare module '@miiajs/core' {
  interface RequestContext {
    user?: User
  }
}

Now ctx.user is User | undefined everywhere - and inside guarded routes you can safely treat it as User.

Variations

Custom header

typescript
private extract = fromHeader('x-auth-token', '')
// reads X-Auth-Token: <raw token>
typescript
private extract = fromCookie('access_token')
// reads Cookie: access_token=<token>

See Cookies for the full cookie API.

typescript
private extract = fromQuery('token')
// reads ?token=<jwt>

You can also accept multiple sources with a fallback:

typescript
private extractHeader = fromHeader()
private extractQuery = fromQuery('token')

async authenticate(ctx: RequestContext) {
  const token = this.extractHeader(ctx) ?? this.extractQuery(ctx)
  if (!token) throw new UnauthorizedException('Missing token')
  // ...
}

Security notes

  • Pin the signing algorithm. verify() accepts only the module's algorithm (default HS256 with a secret, RS256 with a key), so a token re-signed with another algorithm or none is rejected. Set algorithm on JwtModule explicitly, and pass algorithms to verify() only when you must accept more than one. See @miiajs/jwt for the options.
  • Short-lived tokens. Sign with expiresIn set to minutes-to-hours, not days. Use a refresh-token flow or server-side session for longer-lived access.
  • Revocation. JWTs are stateless, so logout is best-effort - you need either short TTLs (the common answer) or a denylist checked on verify.
  • Clock skew. Verification allows no clock skew on exp/nbf, and JwtService does not expose jose's clockTolerance. Keep signer and verifier clocks in sync (NTP).

See also

Edit this page on GitHub