Framework/NestJS

[NestJS] 카카오 소셜 로그인 구현

뚜sh뚜sh 2023. 2. 28. 16:04

프론트에서 보낸 리다이렉트 주소를 가진 controller의 코드

 @Get('/kakao')
  async kakaoAuth(@Req() req: Request, @Res() res: Response) {
    // 프로필을 받아온 다음, 로그인을 처리해야 하는 곳 (oauth.service.ts에서 선언해줌)
    return this.oauthService.oauthLogin(req, res);
  }

 

 

 

위 코드 안에 있는 oauthLogin이라는 함수는 service 안에 있음

  /**
   * 아래 함수는 passport-kakao 없이 카카오 소셜 로그인을 구현할 때 필요한 코드
   */
  async oauthLogin(req: Request) {
  let accessToken;
  try {
    const url = 'https://kauth.kakao.com/oauth/token';
    const options = {
      grant_type: 'authorization_code',
      client_id: REST_API_KEY,
      redirect_uri: REDIRECT_URI,
      code: req.query.code,
    };
    const header = {
      headers: { 'content-type': 'application/x-www-form-urlencoded' },
    };
    const tokenResponse = await firstValueFrom(
      this.httpService.post(url, options, header).pipe(
        map((res) => res.data),
        catchError((err) => {
          throw new BadRequestException();
        }),
      ),
    );
    accessToken = tokenResponse.access_token;
  } catch (err) {
    throw new BadRequestException();
  }
  try {
    const url = 'https://kapi.kakao.com/v2/user/me';
    const header = {
      headers: {
        Authorization: `Bearer ${accessToken}`,
      },
    };
    const response = await firstValueFrom(
      this.httpService.get(url, header).pipe(
        map((response) => response.data),
        catchError((error) => {
          throw new BadRequestException();
        }),
      ),
    );
    console.log(response);
    return response;
  } catch (e) {
    throw new BadRequestException();
  }