728x90
Header에 id:password 식으로 데이터를 담아서 로그인에 사용되는 방식이 있다고 하며, 보안적인 측면에서 body보다 좋다고 한다.
- controller
@Post('login/email')
loginEmail(
@Headers('authorization') rawToken: string, //
) {
// email:password -> base64
// asdfasjdfhkajshdfkjasfdfkaakjhrasndfasdf -> email:password
const token = this.authService.extractTokenFromHeader(rawToken, false);
const credentials = this.authService.decodeBasicToken(token);
return this.authService.loginWithEmail(credentials);
}
@Headers는 nestjs/commons꺼 사용
- service
/**
* Heaer로 부터 토큰을 받을 때
*
* {authorization: 'Basic {token}'}
* {authorization: 'Bearer {token}'}
*/
extractTokenFromHeader(header: string, isBearer: boolean) {
// 'Basic {token}' => [Basic, {token}]
// 'Bearer {token}' => [Bearer, {token}]
const splitToken = header.split(' ');
const prefix = isBearer ? 'Bearer' : 'Basic';
if (splitToken.length !== 2 || splitToken[0] !== prefix) {
throw new UnauthorizedException('잘못된 토큰입니다!');
}
const token = splitToken[1];
return token;
}
/**
* Basic kdfnalfnafa
*
* 1) kdfnalfnafa -> email:password
* 2) email:password -> [email, password]
* 3) {email: email, password: password}
*/
decodeBasicToken(base64String: string) {
const decoded = Buffer.from(base64String, 'base64').toString('utf-8');
const split = decoded.split(':');
if (split.length !== 2) {
throw new UnauthorizedException('잘못된 유형의 토큰입니다!');
}
const email = split[0];
const password = split[1];
return { email, password };
}
async loginWithEmail(user: Pick<UsersModel, 'email' | 'password'>) {
const existingUser = await this.authenticateWithEmailAndPassword(user);
return this.loginUser(existingUser);
}
decoded 부분의 Buffer는 node에서 제공하는 기능이라고함.
const decoded = Buffer.from(디코드할꺼, 'base64').toString('utf-8');
강의 내용을 그대로 적어서 그렇지, controller에서의 작업들은 service에서 하는게 맞다고 개인적으로 생각함.
- base65 인/디코드 사이트
Base64 Decode and Encode - Online
Decode from Base64 format or encode into it with various advanced options. Our site has an easy to use online tool to convert your data.
www.base64decode.org
- 강의
학습 페이지
www.inflearn.com
728x90
'코딩 > Nest.js' 카테고리의 다른 글
커스텀 데코레이터 (1) | 2024.10.20 |
---|---|
Guard 기본적 느낌 (0) | 2024.10.20 |
소셜 로그인 (0) | 2024.06.15 |
GraphQL (미완) (0) | 2024.06.10 |
Swagger (0) | 2024.04.24 |