A progressive Node.js framework for building efficient and scalable server-side applications.
A project demonstrating how to use Nest.js with TypeScript for authentication, including JWT implementation.
- Authentication with JWT (JSON Web Token).
- Secure routes with guard.
- User registration and login.
- Clone the repository:
git clone https://github.com/raihanwebmaster/Nest-JS-Authentication.git
- Navigate to the project directory:
cd Nest-JS-Authentication
- Install dependencies:
npm install
- Start the development server:
npm run start:dev
- The server will start on
http://localhost:3000
.
src/
: Contains the source code for the Nest.js application.test/
: Contains the test code for the application.
This project uses JWT for authentication. Below are some examples and configurations to help you get started.
The JWT configuration is defined in src/auth/auth.module.ts
:
import { Module } from '@nestjs/common';
import { JwtModule } from '@nestjs/jwt';
import { AuthService } from './auth.service';
import { AuthController } from './auth.controller';
import { UsersModule } from '../users/users.module';
import { PassportModule } from '@nestjs/passport';
import { JwtStrategy } from './jwt.strategy';
@Module({
imports: [
UsersModule,
PassportModule,
JwtModule.register({
secret: 'your_jwt_secret_key',
signOptions: { expiresIn: '60s' },
}),
],
controllers: [AuthController],
providers: [AuthService, JwtStrategy],
})
export class AuthModule {}
To protect routes using JWT, you can use the @UseGuards
decorator along with the JwtAuthGuard
:
import { Controller, Get, UseGuards, Request } from '@nestjs/common';
import { JwtAuthGuard } from './auth/jwt-auth.guard';
@Controller('profile')
export class ProfileController {
@UseGuards(JwtAuthGuard)
@Get()
getProfile(@Request() req) {
return req.user;
}
}
JWT tokens are generated during the login process. Here is an example of the login function in the auth.service.ts
:
import { Injectable } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { UsersService } from '../users/users.service';
@Injectable()
export class AuthService {
constructor(
private usersService: UsersService,
private jwtService: JwtService
) {}
async validateUser(username: string, pass: string): Promise<any> {
const user = await this.usersService.findOne(username);
if (user && user.password === pass) {
const { password, ...result } = user;
return result;
}
return null;
}
async login(user: any) {
const payload = { username: user.username, sub: user.userId };
return {
access_token: this.jwtService.sign(payload),
};
}
}
Contributions are welcome! Please open an issue or submit a pull request.
For any inquiries, please reach out to the repository owner.