본문 바로가기
it/nestjs

Nest.js 구글 로그인(1)

by sss24 2023. 1. 11.

출처: https://dev.to/imichaelowolabi/how-to-implement-login-with-google-in-nest-js-2aoa

 

How to Implement Login with Google in Nest JS

In this article, we are going to implement (OAuth) login with google in Nest JS. Coming from Express,...

dev.to

이분 꺼 보고 배웠어요.

먼저 Node.js 를 까신 다음 명령프롬프트(CMD)에 전역으로 nestjs/cli 을 깔아줍니다.

그 다음 nest로 새로운 프로젝트를 만들어 줍니다.

 

$ npm i -g @nestjs/cli
$ nest new project-name

그리고 구글 로그인에 필요한 OAuth 다운로드

npm install --save @nestjs/passport passport passport-google-oauth20 dotenv
npm install -D @types/passport-google-oauth20

npm run start:dev

서버 실행 후 

localhost:3000 접속

-접속화면-

 

- 구글 설정(필수) - 

이거 안하면 구글 데이터 못받아옴.https://console.developers.google.com/ 여기로 들어가서

Google Cloud 옆 화살표 모양 누른다음에 새 프로젝트 생성

자기가 하고 싶은 이름 정하고 

OAuth 동의 화면 - ** 외부로 하세요 나중에 변경가능하니까 괜히 내부했다가 오류 뜰 수도 ..?

빨간 별 되어 있는 부분 다 채우시고 저장 후 계속 4번 하시면 첫 화면으로 돌아오죠?

자기가 만든 프로젝트인지 확인해 주시고 사용자 인증정보- 사용자 인증 정보 만들기-OAuth 클라이언트 ID 눌러줍니다.

웹 애플리케이션으로 설정해주시고 이름 마음대로 하시고, 승인된 자바스크립트 원본에 URL 추가 누르셔서 http://localhost:3000 이거 넣고,승인된 리디렉션 URL 눌러서 http://localhost:3000/google/redirect 이거 넣고 만들기 눌러줍니다.

**수정

01-17 : 구현 도중 에러가 발생해서 URI를 추가해주니 해결l

저는 백서버가 3001번이라 localhost:3001로 했습니다.

그 다음 저 빨간부분 .env 파일만들어서

GOOGLE_CLIENT_ID = "자기꺼"

GOOGLE_SECRET = "자기꺼"

저장

 

파일위치 : src-google.strategy.ts 에 만들고

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

import { Injectable } from '@nestjs/common';

config();

@Injectable()
export class GoogleStrategy extends PassportStrategy(Strategy, 'google') {

  constructor() {
    super({
      clientID: "자기꺼 넣으세여",
      clientSecret: "자기꺼 넣으세여",
      callbackURL: 'http://localhost:3000/google/redirect',
      scope: ['email', 'profile'],
    });
  }

  async validate (accessToken: string, refreshToken: string, profile: any, done: VerifyCallback): Promise<any> {
    const { name, emails, photos } = profile
    const user = {
      email: emails[0].value,
      firstName: name.familyName,
      lastName: name.givenName,
      picture: photos[0].value,
      accessToken
    }
    done(null, user);
  }
}

그 다음 app.controller.ts 수정

import { Body, Controller, Delete, Get, Param, Post, Put, Query, Req, UseGuards } from '@nestjs/common';
import { AppService } from './app.service';
import { AuthGuard } from '@nestjs/passport';

@Controller()
export class AppController {
  getHello(): any {
    throw new Error('Method not implemented.');
  }
  @Get()
  findAll(): string {
    return 'Main Page!';
  }
}
@Controller('google')
export class GoogleController {
  getHello(): any {
    throw new Error('Method not implemented.');
  }
  constructor(private readonly appService: AppService) {}

  @Get()
  @UseGuards(AuthGuard('google'))
  async googleAuth(@Req() req) {}

  @Get('redirect')
  @UseGuards(AuthGuard('google'))
  googleAuthRedirect(@Req() req) {
    return this.appService.googleLogin(req)
  }
}


app.service.ts 도 수정해줍니다.
import { Injectable } from '@nestjs/common';

@Injectable()
export class AppService {
  getHello(): string {
    throw new Error('Method not implemented.');
  }
  googleLogin(req) {
    if (!req.user) {
      return 'No user from google'
    }

    return {
      message: 'User information from google',
      user: req.user
    }
  }
}

그 다음 app.module.ts 수정

import { MiddlewareConsumer, Module, NestModule } from '@nestjs/common';
import { AppController} from './app.controller';
import { AppService } from './app.service';
import { GoogleStrategy } from './google.strategy'


@Module({
  imports: [],
  controllers: [AppController],
  providers: [AppService, GoogleStrategy],
})
export class AppModule {}

그 다음 localhost:3000/google 에 들어가면 구글 로그인창 뜸.

그 다음 로그인하면 페이지에 사용자 정보 나오니까 입맛대로 ㄱ.

'it > nestjs' 카테고리의 다른 글

Nest.JS MQTT 통신 브로커 연결  (2) 2023.05.03
Next.js( react-slick )  (1) 2023.03.23
JWT 순서  (3) 2023.02.16
JWT Token  (0) 2023.02.02
typescript로 날씨 api 가져오기  (0) 2023.01.19

댓글