google 계정으로 회원가입/로그인
google auth 관련 패키지 설치
npm install @types/passport-google-oauth2 passport-google-oauth2
환경변수 파일과 app.module 유효성검사 부분에
GOOGLE_AUTH_CLIENT_ID
GOOGLE_AUTH_CLIENT_SECRET
GOOGLE_AUTH_CLIENT_URL
을 추가해준다.
구글 클라우드 콘솔 > 프로젝트 선택 > 프로젝트 없다면 프로젝트 생성 > 생성한 프로젝트를 선택 > API 및 서비스 > 사용자 인증 정보 > OAuth 2.0 클라이언트 ID 가 없다면 사용자 인증 정보 만들기로 생성
localhost:3000 / localhost:3000/api/google/callback( = GOOGLE_AUTH_CALLBACK_URL ) 각각 입력
생성된 클라이언트를 클릭 > Additional information 에 ID와 비밀번호가 있다.
환경변수 셋팅이 끝나면
google 인증에 사용할 stategy와 guard를 생성한다.
생성한 strategy는 module providers에 추가
//google-auth.strategy.ts 파일
@Injectable()
export class GoogleAuthStrategy extends PassPortStrategy(Strategy, 'google') { // 여기서 Strategy는 'passport-google-oauth2' 패키지로부터 가져온다.
constructor(
private readonly configService: ConfigService,// PassportStrategy google 관련 데이터 연동할때 환경변수 사용
){
super({ // PassPortStrategy의 파라미터 설정
//Google OAuth2를 처리하는 데 필요한 클라이언트 ID, 클라이언트 시크릿, 콜백 URL, 스코프 등의 정보를 전달
clientID: configService.get('GOOGLE_AUTH_CLIENT_ID'),
clientSecret: configService.get('GOOGLE_AUTH_CLIENT_SECRET'),
callbackURL: configService.get('GOOGLE_AUTH_CALLBACK_URL'),
scope: ['profile', 'email']
});
}
}
async validate(
_accessToken: string, // 사용자 인증에 성공했을 때 발급되는 액세스 토큰
_refreshToken: string, // 사용자 인증에 성공했을 때 발급되는 리프레시 토큰
profile: any, //사용자 인증이 성공하고 Google에서 제공하는 사용자 정보가 담긴 객체
done: VerifyCallback // 콜백 함수를 호출하여 Passport에게 사용자 인증이 성공했음을 알려줌
): Promise<any>{
console.log(profile);
}
//google-auth.guard.ts 파일
@Injectable()
export class GoogleAuthGuard extends AuthGuard('google'){
}
auth.module provider에 strategy 추가
api 매소드 생성
//auth.controller.ts 파일
+
@Get('google')
@HttpCode(200)
@UseGuards(GoogleAuthGuard)
async googleLogin(): Promise<any> {
return HttpStatus.OK;
}
@Get('google/callback')
@HttpCode(200)
@UseGuards(GoogleAuthGuard)
async googleCallback(): Promise<any> {
}