2024. 7. 5. 23:06ใTIL
๐กPassport
1.์์
- Passport๋ ๊ฐ์ฅ ์ธ๊ธฐ ์๋ node.js ์ธ์ฆ ๋ผ์ด๋ธ๋ฌ๋ฆฌ๋ก, ์ปค๋ฎค๋ํฐ์์ ๊ฐ์ฅ ์ ์๋ ค์ ธ ์์ผ๋ฉฐ ๋ง์ ํ๋ก๋์ ์ดํ๋ฆฌ์ผ์ด์ ์์ ์ฑ๊ณต์ ์ผ๋ก ์ฌ์ฉ๋๊ณ ์๋ค.
- @nestjs/passport ๋ชจ๋์ ์ฌ์ฉํ์ฌ NestJS์์ ์ธ์ฆ๋ก์ง์ ๊น๋ํ๊ฒ ๊ตฌํํ ์ ์๋ค.
2.ํน์ง
- ๋ค์ํ ์ธ์ฆ ๋ฐฉ์ ์ฌ์ฉ๊ฐ๋ฅ : Passport๋ ๋ก์ปฌ ๋ก๊ทธ์ธ, OAuth, JWT ๋ฑ ๋ค์ํ ์ธ์ฆ ๋ฐฉ์์ ์ง์ํ๋ค.
- ๋ฏธ๋ค์จ์ด๋ฅผ ๊ธฐ๋ฐ : Express ๋ฏธ๋ค์จ์ด๋ก ๋์ํ๋ฉฐ, NestJS์ ๋ฏธ๋ค์จ์ด์ ์ฝ๊ฒ ํตํฉ๊ฐ๋ฅํ๋ค.
- ์ ์ฐ์ฑ : ์ฌ์ฉ์ ์ ์ ์ ๋ต์ ์ฝ๊ฒ ๊ตฌํํ ์ ์๋ค.
3. NestJS์์ Passport ์ฌ์ฉํ๊ธฐ
- ๋ก๊ทธ์ธํ๊ณ JWTํ ํฐ ๋ฐ๊ธ๋ฐ๊ธฐ
1) ์ ํ๋ก์ ํธ ์์ฑ
nest new newproject
2) ํ์ํ ํจํค์ง ์ค์
npm install @nestjs/passport passport passport-local @nestjs/jwt passport-jwt
3) Module ์์ฑ
- Auth ๋ชจ๋ ์์ฑ
nest g module auth
nest g service auth
nest g controller auth
4) JWT ์ ๋ต ์ค์
// auth/jwt.strategy.ts
import { Injectable } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';
import { ExtractJwt, Strategy } from 'passport-jwt';
import { ConfigService } from '@nestjs/config';
@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
constructor(private readonly configService: ConfigService) {
super({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
ignoreExpiration: false,
secretOrKey: configService.get<string>('JWT_SECRET'),
});
}
async validate(payload: any) {
return { userId: payload.sub, username: payload.username };
}
}
5) AuthService ์ค์
// auth/auth.service.ts
import { Injectable } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
@Injectable()
export class AuthService {
constructor(private readonly jwtService: JwtService) {}
async login(user: any) {
const payload = { username: user.username, sub: user.userId };
return {
access_token: this.jwtService.sign(payload),
};
}
}
6) Auth ๋ชจ๋ ์ค์
// auth/auth.module.ts
import { Module } from '@nestjs/common';
import { JwtModule } from '@nestjs/jwt';
import { PassportModule } from '@nestjs/passport';
import { AuthService } from './auth.service';
import { AuthController } from './auth.controller';
import { JwtStrategy } from './jwt.strategy';
import { ConfigModule, ConfigService } from '@nestjs/config';
@Module({
imports: [
PassportModule,
JwtModule.registerAsync({
imports: [ConfigModule],
inject: [ConfigService],
useFactory: async (configService: ConfigService) => ({
secret: configService.get<string>('JWT_SECRET'),
signOptions: { expiresIn: '60s' },
}),
}),
],
providers: [AuthService, JwtStrategy],
controllers: [AuthController],
})
export class AuthModule {}
7) AuthController ์ค์
// auth/auth.controller.ts
import { Controller, Post, Request, UseGuards } from '@nestjs/common';
import { AuthService } from './auth.service';
import { LocalAuthGuard } from './local-auth.guard';
@Controller('auth')
export class AuthController {
constructor(private readonly authService: AuthService) {}
@UseGuards(LocalAuthGuard)
@Post('login')
async login(@Request() req) {
return this.authService.login(req.user);
}
}
8) LocalAuthGuard ์ค์
// auth/local-auth.guard.ts
import { Injectable, ExecutionContext } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
@Injectable()
export class LocalAuthGuard extends AuthGuard('local') {
async canActivate(context: ExecutionContext): Promise<boolean> {
const result = (await super.canActivate(context)) as boolean;
const request = context.switchToHttp().getRequest();
await super.logIn(request);
return result;
}
}
9) UsersService ์ค์
// users/users.service.ts
import { Injectable } from '@nestjs/common';
@Injectable()
export class UsersService {
private readonly users = [
{
userId: 1,
username: 'test',
password: 'test',
},
];
async findOne(username: string): Promise<any> {
return this.users.find(user => user.username === username);
}
}
10) LocalStrategy ์ค์
// auth/local.strategy.ts
import { Strategy } from 'passport-local';
import { PassportStrategy } from '@nestjs/passport';
import { Injectable, UnauthorizedException } from '@nestjs/common';
import { AuthService } from './auth.service';
@Injectable()
export class LocalStrategy extends PassportStrategy(Strategy) {
constructor(private readonly authService: AuthService) {
super();
}
async validate(username: string, password: string): Promise<any> {
const user = await this.authService.validateUser(username, password);
if (!user) {
throw new UnauthorizedException();
}
return user;
}
}
'TIL' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
TIL (SQL๋ฌธ๋ฒ - JOIN ) (0) | 2024.07.09 |
---|---|
TIL ( Injection ) (0) | 2024.07.08 |
TIL( Nest.js - IoC, DI ) (0) | 2024.07.04 |
TIL (DTO) (0) | 2024.07.03 |
TIL( TypeScript - Utility type ) (0) | 2024.07.02 |