{"id":"21fcfc82886bd754","repo":"nestjs/nest","slug":"unauthorized","errorCode":null,"errorMessage":"Unauthorized","messagePattern":"Unauthorized","errorType":"http","errorClass":"UnauthorizedException","httpStatus":401,"severity":"error","filePath":"integration/graphql-code-first/src/common/guards/auth.guard.ts","lineNumber":14,"sourceCode":"import {\n  CanActivate,\n  ExecutionContext,\n  Injectable,\n  UnauthorizedException,\n} from '@nestjs/common';\nimport { GqlExecutionContext } from '@nestjs/graphql';\n\n@Injectable()\nexport class AuthGuard implements CanActivate {\n  async canActivate(context: ExecutionContext): Promise<boolean> {\n    const gqlContext = GqlExecutionContext.create(context);\n    if (gqlContext) {\n      throw new UnauthorizedException();\n    }\n    return true;\n  }\n}\n","sourceCodeStart":1,"sourceCodeEnd":19,"githubUrl":"https://github.com/nestjs/nest/blob/6ec0e2783d15290732447f304d8549b591b9749e/integration/graphql-code-first/src/common/guards/auth.guard.ts#L1-L19","documentation":"Thrown by a GraphQL auth guard (integration fixture) via NestJS `UnauthorizedException` (HTTP 401). The guard calls `GqlExecutionContext.create(context)` and unconditionally throws whenever a GraphQL context exists, demonstrating how to reject unauthenticated GraphQL requests. Because the created context object is always truthy, this fixture always rejects.","triggerScenarios":"Executing any resolver method decorated with `@UseGuards(AuthGuard)` — e.g. the `recipe(id: String!)` query in recipes.resolver.ts:18 — against this integration fixture.","commonSituations":"Integration/e2e tests asserting that GraphQL guards emit a 401; copying this fixture into real code without replacing the stub condition with real auth checks.","solutions":["If this is your own guard, replace `if (gqlContext)` with a real authentication check (e.g. validate a JWT or session from `context.getContext().req.headers.authorization`).","If you are running the integration test, send the request the test expects (no/invalid credentials) and assert the 401.","Ensure the guard is only applied where authentication is actually required."],"exampleFix":"// before\nasync canActivate(context: ExecutionContext): Promise<boolean> {\n  const gqlContext = GqlExecutionContext.create(context);\n  if (gqlContext) {\n    throw new UnauthorizedException();\n  }\n  return true;\n}\n// after\nasync canActivate(context: ExecutionContext): Promise<boolean> {\n  const ctx = GqlExecutionContext.create(context).getContext();\n  const authHeader = ctx.req?.headers?.authorization;\n  if (!authHeader) {\n    throw new UnauthorizedException('Missing auth token');\n  }\n  return true;\n}","handlingStrategy":"try-catch","validationCode":"// Validate auth before invoking a guarded resolver from the client\nconst res = await fetch('/graphql', {\n  method: 'POST',\n  headers: { 'content-type': 'application/json', authorization: `Bearer ${token}` },\n  body: JSON.stringify({ query: '{ recipe(id:\"1\"){ id } }' }),\n});\nif (res.status === 401) { /* re-login */ }","typeGuard":"import { UnauthorizedException } from '@nestjs/common';\nfunction isUnauthorized(e: unknown): e is UnauthorizedException {\n  return e instanceof UnauthorizedException;\n}","tryCatchPattern":"try {\n  return await this.recipesService.findOneById(id);\n} catch (e) {\n  if (e instanceof UnauthorizedException) {\n    // redirect to login\n  }\n  throw e;\n}","preventionTips":["Always send a valid Authorization header from the client.","Implement a global auth guard and exempt only public routes with `@Public()`.","Return meaningful messages from `UnauthorizedException` instead of an empty body."],"tags":["graphql","authentication","guard","authorization","nestjs"],"analyzedSha":"6ec0e2783d15290732447f304d8549b591b9749e","analyzedAt":"2026-08-03T17:42:23.673Z","schemaVersion":2}