글 작성자: 망고좋아
반응형

🎯 구글 로그인 구현하기

📝 구글 로그인 구현 순서

  • 구글 클라우드 플랫폼 프로젝트 생성
  • API 및 서비스 → OAuth 동의 화면 설정
  • 사용자 인증정보 → OAuth 클라이언트 ID 만들기
  • passport-google-oauth20 연동

 

📝 passport-google-oauth20

  • passport-strategy 인터페이스의 구글 로그인 구현체
  • OAuth 인증을 구현하기 위해서는 인증 요청, 데이터 수신 등의 복잡한 작업 필요하다.
  • passport-google-oauth20는 손쉽게 구글 OAuth 2.0을 구현해 주는 패키지이다.

 

📕 passport-google-oauth20 작성

🛠 google strategy

const GoogleStrategy = require('passport-google-oauth20').Strategy;

const config = {
    clientID: 'clientID',
    clientSecret: 'clientSecret',
    callbackURL: 'callbackUrl',
};

...
new GoogleStrategy(config, (accessToken, refreshToken, profile, done) => {
    const { email, name } = profile._json;
    ...
    // create or update user
  • 구글 로그인이 완료된 후 결과를 전달받는 부분
  • OAuth 클라이언트 설정값 및 완료 결과를 전달받을 callbackURL을 config로 설정
  • accessToken, refreshToken 은 다른 구글 API들을 사용하기 위한 토큰 (본 프로젝트에서는 사용하지 않음)
  • profile은 전달받은 유저 정보. 이를 이용해 유저를 생성하거나 OAuth 정보를 업데이트함

 

🛠 authenticate

passport.use(google);

// ---
router.get('/google',
    // 구글페이지로 가서 로그인
    passport.authenticate('google', {
        scope: ['profile', 'email']
    }));

    router.get('/google/callback',
        passport.authenticate('google', {
            failureRedirect: '/login'
        }), (req, res, next) => {

        res.redirect('/');
});
  • /auth/google 접근 시 자동으로 구글 로그인 페이지로 넘어간다.
  • 로그인 완료 후 로그인 정보를 /auth/google/callback으로 전달해 준다. (config에 설정된 주소)
  • 전달받은 데이터는 strategy에서 처리 처리가 완료되면 request handler 실행

 

🛠 login.pug

...
td: a(href="/auth/google") 구글로 로그인하기
  • /auth/google로 link 시 passport 가 자동으로 구글 로그인 페이지로 이동시켜 주고, 로그인 결과를 /auth/google/callback으로 전달해 준다.
반응형