[nest.js] 쿠키를 이용한 인증처리

어느 정도 로긴을 구현한 상태를 가정으로 설명합니다.

관련 패키지 설치

npm install --save cookie-parser
npm install --save-dev @types/cookie-parser

로긴 소스코드 수정

@Post( '/login' )
	async login(
		@Body( ValidationPipe ) dto: UserDTO,
		@Res( { passthrough : true } ) res : Response
	) : Promise<object>
	{
		const accessToken : object = await this.authService.login( dto );
        //쿠키에 저장될 이름을 Authentication 로 지정
		res.cookie(
			'Authentication',
			accessToken['token'],
			{
				domain : 'localhost',
				path : '/',
				httpOnly : true,//브라우저 외 접근 금지, 보안유리
				maxAge : 0.5 * 60 * 60 * 1000//0.5 hour//life time
			}
			);
		return accessToken;
	}

jwt strategy 소스코드 수정

import { Injectable, NotFoundException, UnauthorizedException } from "@nestjs/common";
import { PassportStrategy } from "@nestjs/passport";
import { InjectRepository } from "@nestjs/typeorm";
import { Repository } from "typeorm";
import { User } from "../user/user.entity";

//쿠키에서 원하는 값 꺼내는 함수
let cookieExtractor = function( req )
{
	var token = null;
	if( req && req.cookies )
	{
    	//로긴시 사용한 쿠키명 : Authentication
		token = req.cookies["Authentication"] || req.header;
	}
	return token;
};

@Injectable()
export class JwtStrategy extends PassportStrategy( Strategy )
{
	constructor( @InjectRepository( User ) private userRepository : Repository<User> )
	{
		super(
			{
				secretOrKey : "secret1234",
				jwtFromRequest : cookieExtractor,
			} );
	};

	async validate( payload ) : Promise<User>
	{
		const { id } = payload;
		const user : User = await this.userRepository.findOneBy( { id : id } );
		if ( !user )
			throw new UnauthorizedException( "not exist user" );

		return user;
	}
}

테스트

@Get( '/cookies' )
@UseGuards( AuthGuard() )//인증된 사용자만 접근 가능
getCookies( @Req() req : Request, @Res() res : Response ) : any
{
	return res.send( req.cookies['Authentication'] );
}

postmant 으로 호출, Bearer Token 을 사용하지 않아도 자동으로 쿠키에 있는 토큰으로 인증처리됨

쿠키에 자동으로 토큰이 들어감. 노출되도 사용할 수 없도록 암호화처리
api 리턴값에는 토큰값 원본 그대로

Subscribe to X세대 신입사원

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
jamie@example.com
Subscribe
774-86-01972 cinnabar.3d@gmail.com