This package is for self use. Feel free to use it if you find it useful.
It provides a simple and easy to use JWT authentication module for NestJS.
# required packages
npm install @nestjs/jwt @nestjs/passport passport passport-jwt
# install the package
npm install nestlibs-jwt-auth
Import the JwtAuthModule
in your root module and call the forRoot
method with the module name and the configuration object.
import { JwtAuthModule } from 'nestlibs-jwt-auth';
@Module({
imports: [
JwtAuthModule.forRoot('main-auth', {
accessTokenSecret: 'access-token-secret',
refreshTokenSecret: 'refresh-token-secret',
strategyConfig: {
validate: (_req, payload) => {
console.log('Jwt payload: ', payload);
return payload;
},
},
}),
],
})
export class AppModule {}
import { generateJwtAuthGuard } from 'nestlibs-jwt-auth';
export const { JwtAuthGuard, UseJwtAuthGuard, UseAuthUser } =
generateJwtAuthGuard('main');
app.controller.ts
import { Controller, Get } from '@nestjs/common';
import { UseJwtAuthGuard } from '../auth';
@Controller()
export class UserController {
constructor(private prisma: PrismaService) {}
@UseJwtAuthGuard()
@Get('users')
async getUsers(@UseAuthUser() user: User) {
return this.prisma.user.findMany();
}
}
app.resolver.ts
import { Resolver, Query } from '@nestjs/graphql';
import { UseJwtAuthGuard } from '../auth';
@Resolver()
export class UserResolver {
constructor(private prisma: PrismaService) {}
@UseJwtAuthGuard()
@Query(() => [User])
async users(@UseAuthUser() user: User) {
return this.prisma.user.findMany();
}
}
import { InjectJwtAuthService, JwtAuthService } from 'nestlibs-jwt-auth';
@Injectable()
export class AppService {
constructor(
@InjectJwtAuthService('main-auth')
private readonly jwtAuthService: JwtAuthService
) {}
async login() {
const isPasswordValid = true;
if (!isPasswordValid) throw new UnauthorizedException('Invalid password');
const accessToken = await this.jwtAuthService.generateAccessToken({ id: 1 });
const refreshToken = await this.jwtAuthService.generateRefreshToken({ id: 1 });
...
}
}
Signs the payload and returns the token.
Verifies the token and returns the payload.
Decodes the token and returns the payload.
Generates an access token and returns the token.
Generates a refresh token and returns the token.
Verifies the access token and returns the payload.
Verifies the refresh token and returns the payload.