Search

Google OAuth

Google 로그인을 구현하기 위해서 아래 패키지 설치가 필요하다.
npm i passport-google-oauth20 npm i -D @types/passport-google-oauth20
JavaScript
복사

strategy 클래스 작성

nestjs에서 구글 로그인을 구현하기 위해서는 GoogleStrategy 클래스를 정의해야 한다.
PassPortStrategy 클래스를 상속받아 구글 인증에 필요한 설정을 하고,
validate 메서드를 통해 구글에서 받은 토큰과 프로필 정보를 검증 및 처리한다.
@Injectable() export class GoogleStrategy extends PassportStrategy(Strategy, 'google') { constructor() { super({ clientID: process.env.GOOGLE_CLIENT_ID, clientSecret: process.env.GOOGLE_CLIENT_SECRET, callbackURL: process.env.GOOGLE_REDIRECT_URL, scope: ['email', 'profile'], } ); } // refreshToken를 얻기 위한 필수 코드 authorizationParams(): {[key: string]: string; } { return ({ access_type: 'offline', prompt: 'select_account', }); } async validate( accessToken: string, refreshToken: string, profile: Profile, ): Promise<any> { const { id, name, emails } = profile; return { provider: 'google', providerId: id, name: name.givenName, email: emails[0].value, }; } } // env // GOOGLE_CLIENT_ID=808480287003-460oqaeleufj4il4o9kb4m3n1oug6g9p.apps.googleusercontent.com // GOOGLE_CLIENT_SECRET=보안을위해가림 // GOOGLE_REDIRECT_URL=http://localhost:3000/auth/google {"id":"106767384005656562156","displayName":"원주연","name":{"familyName":"원","givenName":"주연"},"emails":[{"value":"dnjswndus95@gmail.com","verified":trphotos":[{"value":"https://lh3.googleusercontent.com/a/ACg8ocJA_3lQ3buX7uGDl7pfsUMy8loD5plel-gW_ZlQhO_mgNsTXg=s96-c"}],"provider":"google","_raw":"{\n \"sub\": \"106767384005656562156\",\n \"name\": \"원주연\",\n \"given_name\": \"주연\",\n \"family_name\": \"원\",\n \"picture\": \"https://lh3.googleusert.com/a/ACg8ocJA_3lQ3buX7uGDl7pfsUMy8loD5plel-gW_ZlQhO_mgNsTXg\\u003ds96-c\",\n \"email\": \"dnjswndus95@gmail.com\",\n \"email_verified\": true\n}","_json":{"sub":"106767384005656562156","name":"원주연","given_name":"주연","family_name":"원","picture":"https://lh3.googleusercontent.com/a/ACg8ocJA_3lQ3buX7usUMy8loD5plel-gW_ZlQhO_mgNsTXg=s96-c","email":"dnjswndus95@gmail.com","email_verified":true}} ==========================
TypeScript
복사