저장을 습관화
에러 기록 - passport를 이용하여 로그인 시도 중 발생하는 401 Unauthorized 에러 본문
- 증상
nest.js 프레임워크에서 로그인 기능을 만들기 위해
인증 용 가드 작성 중
가드가 참조할 strategy를 작성하였으니 계속해서 401 unauthorized가 발생하는 문제
- 원인과 해결
각 구간마다 로그를 찍어서 에러가 발생하는 부분을 확인
local-auth.guard.ts
import { ExecutionContext, Injectable } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
@Injectable()
export class LocalAuthGuard extends AuthGuard('local') {
async canActivate(context: ExecutionContext): Promise<boolean> {
console.log('로컬 어스 가드 1');
const can = await super.canActivate(context);
console.log(`여기서 부터 확인할 것`);
console.log(`${can}`);
console.log(`여기까지 확인할 것`);
if (can) {
console.log('로컬 어스 가드 2');
const request = context.switchToHttp().getRequest();
console.log('login for cookie');
await super.logIn(request);
}
console.log('로컬 어스 가드 3');
return true;
}
}
local-strategy.ts
import { Strategy } from 'passport-local';
import { Injectable, UnauthorizedException } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';
import { AuthService } from './auth.service';
@Injectable()
export class LocalStrategy extends PassportStrategy(Strategy) {
constructor(private authService: AuthService) {
super({ usernameFiled: 'email', passwordFiled: 'password' });
console.log('로컬 전략 1');
}
async validate(email: string, password: string, done: CallableFunction) {
console.log('로컬 전략 2');
const user = await this.authService.validateUser(email, password);
if (!user) {
throw new UnauthorizedException(); // 401 에러 발생, http-exception.filter에서 에러 로그 출력
}
console.log('로컬 전략 3');
return done(null, user); // local-serializer.ts로 전달
}
}
이 외에도 서비스, 시리얼라이저도 있었으나
로그가 '로컬 어스 가드 1'밖에 찍히지 않았음
'로컬 어스 가드 1' 다음은 AuthGuard의 canActivate 함수이고,
이는 local-strategy.ts인데, 로그 '로컬 전략 1'도 찍히지 않은 것으로 봐서
super(), 즉 PassportStrategy() 함수가 제대로 동작하지 않는 것으로 판단하였음
passport.strategy.d.ts는 아래와 같음
import { Type } from '../interfaces';
export declare function PassportStrategy<T extends Type<any> = any>(
Strategy: T,
name?: string | undefined,
callbackArity?: true | number,
): {
new (...args: any[]): InstanceType<T>;
};
여기서 어디를 잘못쓴걸까.. 계속해서 들여다보면서 고민했었는데
원인은 'usernameField', 'passwordField'를
'usernameFiled', 'passwordfiled'라고 적어서 발생한 문제였음..
단어 잘못쓰면 밑줄 그어주는 코드 스펠 체커 사용하고 있는데도
밑줄이나 뭐 잘못적었다 이런 표시가 전혀 없어서
객체값명 잘못적은게 원인일줄은 진짜 몰랐음..
더 큰일이 아니어서 다행이긴 하지만 너무 허무하다
'공부 > node.js' 카테고리의 다른 글
NestJS - TypeORM CRUD (0) | 2023.12.29 |
---|---|
NestJS - TypeORM 트랜잭션 (0) | 2023.12.28 |
NestJS의 라이프 사이클 (0) | 2023.12.20 |
에러 기록 - TypeError: Cannot read properties of undefined (reading 'config') (0) | 2023.12.19 |
에러 기록 - AlreadyHasActiveConnectionError: Cannot create a new connection named "default", because connection with such name already exist and it now has an active connection session. (0) | 2023.11.27 |