✨ 로그인 과정

Untitled

1. 로그인 완료 시 콜백 주소에 전달된 인가 코드를 백엔드에 전달

2. 인가 코드와 함께 네이버에 접근할 수 있는 엑세스 토큰을 요청

3. 받은 엑세스 토큰으로 네이버에 유저 정보 요청

4. 받은 유저 정보가 DB에 없다면 저장

5. 유저 이름과 이메일을 payload에 담아 엑세스 토큰 발급해 프론트에게 전달

✨ 개발 과정

1. 네이버 개발자 센터에서 client ID와 client Secret 키를 가져온다.

Untitled

2. 서버에서 요청을 보낼 수 있게 axios을 다운 받았다.

yarn add axios
yarn add @nestjs/axios

3. 네이버에 접근 토큰 요청을 보낸다.

: 요청하는 access token은 네이버 유저 정보를 요청하기 위한 토큰이다.

async getNaverAccessToken(code: string): Promise<string> {
    const url = '<https://nid.naver.com/oauth2.0/token>';
    const clientId = this.configService.get('NAVER_CLIENT_ID');
    const clientSecret = this.configService.get('NAVER_CLIENT_SECRET');

    try {
      return (
        await this.httpService.axiosRef.post(
          url,
          {},
          {
            params: {
              grant_type: 'authorization_code',
              client_id: clientId,
              client_secret: clientSecret,
              code: code,
            },
            headers: { 'X-Naver-Client-Id': clientId, 'X-Naver-Client-Secret': clientSecret },
          }
        )
      ).data.access_token;
    } catch (error) {
      throw new HttpException('Failed to get Naver access token', HttpStatus.INTERNAL_SERVER_ERROR);
    }
  }

4. 네이버에 유저 정보를 요청한다.

async getNaverUser(accessNaverToken: string): Promise<UserNaverDto> {
    try {
      return (
        await this.httpService.axiosRef.post(
          '<https://openapi.naver.com/v1/nid/me>',
          {},
          { headers: { Authorization: `Bearer ${accessNaverToken}` } }
        )
      ).data.response;
    } catch (error) {
      throw new HttpException('Failed to get Naver user data.', HttpStatus.INTERNAL_SERVER_ERROR);
    }
  }

✨ 아쉬운 점