{"id":"deed89a37b89ec77","repo":"nestjs/nest","slug":"unauthorized-deed89","errorCode":null,"errorMessage":"Unauthorized","messagePattern":"Unauthorized","errorType":"http","errorClass":"UnauthorizedException","httpStatus":401,"severity":"error","filePath":"sample/19-auth-jwt/src/auth/auth.guard.ts","lineNumber":33,"sourceCode":"  constructor(\n    private jwtService: JwtService,\n    private reflector: Reflector,\n  ) {}\n\n  async canActivate(context: ExecutionContext): Promise<boolean> {\n    const isPublic = this.reflector.getAllAndOverride<boolean>(IS_PUBLIC_KEY, [\n      context.getHandler(),\n      context.getClass(),\n    ]);\n    if (isPublic) {\n      // 💡 See this condition\n      return true;\n    }\n\n    const request = context.switchToHttp().getRequest();\n    const token = this.extractTokenFromHeader(request);\n    if (!token) {\n      throw new UnauthorizedException();\n    }\n    try {\n      const payload = await this.jwtService.verifyAsync(token, {\n        secret: jwtConstants.secret,\n      });\n      // 💡 We're assigning the payload to the request object here\n      // so that we can access it in our route handlers\n      request['user'] = payload;\n    } catch {\n      throw new UnauthorizedException();\n    }\n    return true;\n  }\n\n  private extractTokenFromHeader(request: Request): string | undefined {\n    const [type, token] = request.headers.authorization?.split(' ') ?? [];\n    return type === 'Bearer' ? token : undefined;\n  }","sourceCodeStart":15,"sourceCodeEnd":51,"githubUrl":"https://github.com/nestjs/nest/blob/6ec0e2783d15290732447f304d8549b591b9749e/sample/19-auth-jwt/src/auth/auth.guard.ts#L15-L51","documentation":"Error \"Unauthorized\" thrown in nestjs/nest.","triggerScenarios":"Thrown at sample/19-auth-jwt/src/auth/auth.guard.ts:33 when the library encounters an invalid state.","commonSituations":"See trigger scenarios.","solutions":["Send a valid JWT in the Authorization: Bearer <token> header; the guard throws Unauthorized when the token is missing or invalid.","Verify the token has not expired and was signed with the expected secret (jwtConstants.secret).","Ensure the Authorization header is formatted exactly as 'Bearer <token>'."],"exampleFix":"// client request\nfetch('/profile', {\n  headers: { Authorization: `Bearer ${accessToken}` }\n});","handlingStrategy":null,"validationCode":null,"typeGuard":null,"tryCatchPattern":null,"preventionTips":[],"tags":[],"analyzedSha":"6ec0e2783d15290732447f304d8549b591b9749e","analyzedAt":"2026-08-03T17:42:23.673Z","schemaVersion":2}