I am following nest.js official course on authentication and authorization. But I am using graphql code first approach instead of rest api.
This is the code for the access-token.guard.ts FROM the course intended for a REST API
import {
CanActivate,
ExecutionContext,
Inject,
Injectable,
UnauthorizedException,
} from '@nestjs/common';
import { ConfigType } from '@nestjs/config';
import { JwtService } from '@nestjs/jwt';
import { Request } from 'express';
import jwtConfig from 'src/iam/config/jwt.config';
import { REQUEST_USER_KEY } from 'src/iam/iam.constant';
@Injectable()
export class AccessTokenGuard implements CanActivate {
constructor(
private readonly jwtService: JwtService,
@Inject(jwtConfig.KEY)
private readonly jwtConfiguration: ConfigType<typeof jwtConfig>,
) {}
async canActivate(context: ExecutionContext): Promise<boolean> {
const request = context.switchToHttp().getRequest();
const token = this.extractTokenFromHeader(request);
if (!token) {
throw new UnauthorizedException();
}
try {
const payload = await this.jwtService.verifyAsync(
token,
this.jwtConfiguration,
);
request[REQUEST_USER_KEY] = payload;
console.log(payload);
} catch {
throw new UnauthorizedException();
}
return true;
}
private extractTokenFromHeader(request: Request): string | undefined {
const [_, token] = request.headers.authorization?.split('') ?? [];
return token;
}
}
the iam.constant.ts file includes the following
typescript export const REQUEST_USER_KEY = 'user';