티스토리 뷰

728x90
반응형

구글로그인 구현하기

구글로그인 패스포트 모듈 설치

$ npm i --save passport-google-oauth20
$ npm i -D @types/passport-google-oauth20

구글클라우드에서 API 키 발급받기

아래사진은 구글 로그인 과정을 나타낸다.

출처: codementor community

1.Google Cloud 프로젝트 만들기
2.API 및 서비스 이동
3.'OAuth 동의 화면' 메뉴 클릭

  • 3-1. 1단계. OAuth 동의화면

    • 앱이름 / 사용자 지원 이메일 / 앱도메인/ 승인된 도메인 / 개발자 연락처 정보 입력
    • 2단계. 범위 부분은 민감한 영역을 다루게될경우라서 패스.
    • 3단계. 테스트 사용자: 테스트사용자도 필요없어서 그냥 패스.
  • 3-2. 생성하면 Client IDClient Secret Key 를 생성하는데 둘다 복사하기 특히 시크릿은 꼭 저장해놔야됩니다!

  • 3-3. Client ID, Client Secret, Callback URL 은 모두 .env에 기입합니다.

4.'사용자 인증정보' 메뉴 클릭

  • 4-1. '승인된 자바스크립트 원본' 에는 구글로그인 요청 URL을 기입합니다.
    • 저의 경우에는 로컬호스트로 할거라서 https://localhost:3000 으로 했습니다.
  • 4-2. '승인된 리다이렉션 URI 는 구글로그인을 하려는 요청자에게 로그인 계정이 유효한지를 검증을 요청하는 URI 입니다.

구글 OAuth2.0 로그인 Strategy 만들기

google.strategy.ts

import { Injectable } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { PassportStrategy } from '@nestjs/passport';
import { Strategy, VerifyCallback } from 'passport-google-oauth20';

@Injectable()
export class GoogleLoginStrategy extends PassportStrategy(Strategy, 'google') {
  constructor(private readonly configService: ConfigService) {
    super({
      clientID: configService.get('GOOGLE_CLIENT_ID'),
      clientSecret: configService.get('GOOGLE_CLIENT_SECRET'),
      callbackURL: configService.get('GOOGLE_LOGIN_CALLBACK_URL'),
      scope: ['email', 'profile'],
    });
  }

  async validate(
    accessToken: string,
    refreshToken: string,
    profile: any,
    done: VerifyCallback
  ) {
    const { name, emails } = profile;
    const user = {
      email: emails[0].value,
      name: name.givenName,
      accessToken,
    };

    done(null, user);
  }
}

Controller 만들기

import {
  Controller,
  Post,
  UseGuards,
  Req,
  Res,
  Body,
  Get,
} from '@nestjs/common';
import { AuthService } from './auth.service';
import { Public } from '../decorators/public.decorator';
import { AuthGuard } from '@nestjs/passport';

@Controller('auth')
export class AuthController {
  constructor(private readonly authService: AuthService) {}

  // 구글로그인 리다이렉트
  @Get('google/redirect')
  @UseGuards(AuthGuard('google'))
  async googleLoginRedirect(@Req() req) {
    return this.authService.googleLogin(req);
  }

  // 구글로그인
  @Get('google')
  @UseGuards(AuthGuard('google'))
  async googleLogin(@Req() req) {}
}

auth.service.ts

import { Injectable, Req } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';

@Injectable()
export class AuthService {
  // 구글로그인
  constructor(private readonly configService: ConfigService) {}

  async googleLogin(@Req() req) {
    if (!req.user) {
      return 'No User from Google';
    }

    return {
      message: 'User Information from google',
      user: req.user, // 로그인한 유저정보를 메시지로 리스폰스
    };
  }
}

참고자료

구글로그인

728x90
반응형
반응형
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함