skip to content

In a NestJS app, how does a guard extending AuthGuard('jwt') end up sending 401, 403 or 500, and where do you customise that failure?

level: seniorimportance: should knowfreq 40%

answer

  1. fail versus error in Passport
  2. one overridable callback method
  3. token problems arrive as info
  4. thrown exceptions keep their status

basics

~20 s

Token problems and a validate() that returns null reach handleRequest() with no user and become UnauthorizedException, a 401. An exception thrown in validate() is rethrown unchanged, so ForbiddenException gives 403 and a plain Error gives 500.

solid answer

~40 s

`AuthGuard` calls `passport.authenticate()` with a custom callback that ends in `handleRequest(err, user, info, context, status)`. The default throws `err || new UnauthorizedException()` when there is no user. A missing token, a bad signature or an expired token is a Passport *failure*: `err` is null, `user` is false and `info` holds the reason (an Error 'No auth token', or the verification error such as 'jwt expired'), so the client gets 401; `validate()` returning `null` lands in the same branch. An exception thrown in `validate()` is a Passport *error* and is rethrown as is: an `HttpException` keeps its status, anything else becomes a logged 500. To change messages or map a strategy's status, override `handleRequest()` in your guard subclass; the guard also copies `info` to `req.authInfo`.

code

typescript · 16 lines
typescript
import { Injectable, UnauthorizedException } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';

@Injectable()
export class JwtAuthGuard extends AuthGuard('jwt') {
  handleRequest(err: any, user: any, info: any) {
    if (err) {
      throw err;
    }
    if (!user) {
      const expired = info instanceof Error && info.message === 'jwt expired';
      throw new UnauthorizedException(expired ? 'Token expired' : 'Authentication required');
    }
    return user;
  }
}

go deeper

for a junior

Know that a missing or invalid token gives 401 by default, and that handleRequest() is the method to override for a different response.

for a middle

Explain Passport's fail versus error paths, what lands in err, user and info, and why an exception from validate() keeps its own status.

for a senior

Show production judgment: never mask server errors as 401, expose only the token-failure detail clients need, and keep 403 decisions out of authentication.

for a principal

Set a team rule for authentication failure bodies and statuses, so every service answers the same way and clients can refresh tokens predictably.

## The path from Passport to a status code `AuthGuard('jwt')` from `@nestjs/passport` is a guard class generated by a mixin. Its `canActivate()` does not return `false` on failure; it either returns `true` or throws. The route to that decision runs through one overridable method: 1. The guard calls `passport.authenticate('jwt', options, callback)` with a **custom callback**. 2. passport-jwt extracts the token, verifies it and calls the verify callback, which runs your `validate()`. 3. Passport ends in one of three ways: **success** (a user), **fail** (no user, with a challenge or reason), or **error** (an exception). 4. The guard stores the third argument on `req.authInfo`, then calls **`handleRequest(err, user, info, context, status)`**. 5. The default `handleRequest()` is: if `err` or no `user`, throw `err || new UnauthorizedException()`; otherwise return the user, which becomes `req.user`. 6. Whatever is thrown travels to Nest's exception layer, which picks the status. ## What each failure looks like in `handleRequest()` | Situation | `err` | `user` | `info` | Default response | |---|---|---|---|---| | no token found by the extractor | `null` | `false` | an `Error` with message `'No auth token'` | 401 | | bad signature, malformed or expired token | `null` | `false` | the verification error (message `'jwt expired'` when expired) | 401 | | `validate()` returns `null` or `false` | `null` | `false` | whatever info the strategy passed, often `undefined` | 401 | | `validate()` throws `ForbiddenException` | that exception | `undefined` | `undefined` | 403 | | `validate()` throws a plain `Error` (database down) | that error | `undefined` | `undefined` | 500, logged | Two observations follow. A token problem is a **failure**, not an error, so it never appears in `err`; it arrives in `info`. And an exception thrown in `validate()` is **rethrown untouched**: an `HttpException` subclass keeps its status, while anything else reaches the default exception filter, which answers `{"statusCode":500,"message":"Internal server error"}` and logs the original error. ## Customising the failure Extend the guard and override `handleRequest()`; it is the documented extension point. - **Different messages.** Inspect `info` to tell an expired token from a missing one and throw `new UnauthorizedException('Token expired')`. Because the argument is a string, the body becomes `{ message, error: 'Unauthorized', statusCode: 401 }`. - **Respecting a strategy's status.** passport-local fails with status 400 when a credential field is missing; the default `handleRequest()` ignores its fifth argument and answers 401. Map `status === 400` to `BadRequestException` if clients should see it. - **Optional authentication.** Return `null` instead of throwing (for example when a route is marked public) and the guard lets the request through with `req.user === null`. - **Keep `err` first.** Rethrow `err` before looking at `user`; otherwise a database outage inside `validate()` is disguised as bad credentials. ## Reading `info` safely `info` is not one fixed type. It may be `undefined` (a `validate()` that returned `null`), an `Error` (a missing or rejected token), or, for a guard built as `AuthGuard(['jwt', 'api-key'])`, an **array** holding each strategy's failure reason, because Passport reports every challenge when a whole chain fails. Code that reads `info.message` should check the shape first, for example with `info instanceof Error`. ## Judgment calls - Mapping every error to 401 is tempting but wrong for outages: clients treat 401 as "your credentials are bad" and may sign the user out, while the fault is the server's. - Returning a different message for an expired token lets a client refresh silently. How much detail to reveal about why a token was rejected is a trade between client convenience and giving probers feedback; a common compromise is to expose "expired" and keep everything else generic. - Throwing `ForbiddenException` from `validate()` (for a locked account, say) works, but it makes the authentication step decide permissions. Keep policy decisions in a separate guard where possible, so the 401 versus 403 rule stays in one place. ## What does not work - Returning `false` from an overridden `canActivate()` on a token problem gives Nest's generic `ForbiddenException`, a 403, which misstates the problem. - Setting Passport's `failureRedirect` or `failureMessage` through `PassportModule.register()`: those apply only when `passport.authenticate()` has no custom callback, and `AuthGuard` always passes one. - Writing an exception filter for token errors: they never become exceptions unless your `handleRequest()` throws one. How a policy guard should choose between 401 and 403 for an authenticated user is covered with role and policy guards; the checks a token verifier must run are covered in the JSON Web Token validation lesson.

  • passport-local fails with status 400 when a field is missing. Why does the client see 401?
    The strategy calls `fail()` with status 400, and Passport hands that status to the guard's callback as the fifth argument of `handleRequest()`. The default implementation ignores it and throws `UnauthorizedException`. Override `handleRequest()` and throw `BadRequestException` when `status === 400` if clients should see it.
  • validate() throws because the user database is down. What should the client see?
    The default guard rethrows the error, the default exception filter answers 500 'Internal server error' and logs it, which is honest: the fault is the server's. Converting it to 401 would tell the client its credentials are bad and may trigger a needless sign-out, so a custom `handleRequest()` should rethrow `err` before checking `user`.
  • Where else does the failure reason end up besides handleRequest()?
    The guard's Passport callback copies the third argument to `req.authInfo` on every outcome before calling `handleRequest()`. On success it carries any info the strategy passed, such as the second element of an array returned from `validate()`.

  • AuthGuard returns false for a bad token and Nest turns that into 403
  • An expired token makes AuthGuard('jwt') answer 403 Forbidden
  • validate() returning null crashes the request with a 500
  • AuthGuard converts any exception thrown in validate() into a 401
  • handleRequest() runs only on success, so failures cannot be customised there
  • An exception filter is the place to catch passport-jwt's expired-token error