Skip to content

A project demonstrating how to use Nest.js with TypeScript for authentication, including JWT implementation.

Notifications You must be signed in to change notification settings

raihanwebmaster/Nest-JS-Authentication

Repository files navigation

Nest Logo

A progressive Node.js framework for building efficient and scalable server-side applications.

NPM Version Package License NPM Downloads CircleCI Coverage Discord Backers on Open Collective Sponsors on Open Collective Support us

Nest-JS-Authentication

A project demonstrating how to use Nest.js with TypeScript for authentication, including JWT implementation.

Features

  • Authentication with JWT (JSON Web Token).
  • Secure routes with guard.
  • User registration and login.

Installation

  1. Clone the repository:
    git clone https://github.com/raihanwebmaster/Nest-JS-Authentication.git
  2. Navigate to the project directory:
    cd Nest-JS-Authentication
  3. Install dependencies:
    npm install

Usage

  1. Start the development server:
    npm run start:dev
  2. The server will start on http://localhost:3000.

Project Structure

  • src/: Contains the source code for the Nest.js application.
  • test/: Contains the test code for the application.

Authentication with JWT

This project uses JWT for authentication. Below are some examples and configurations to help you get started.

Configuration

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 {}

Usage in Controllers

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;
  }
}

Generating JWT Tokens

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),
    };
  }
}

Contributing

Contributions are welcome! Please open an issue or submit a pull request.

Contact

For any inquiries, please reach out to the repository owner.

About

A project demonstrating how to use Nest.js with TypeScript for authentication, including JWT implementation.

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published