0

MEAN 스택을 사용하는 REST API를 사용하고 Passport JS 인증을 관리하는 응용 프로그램에서 작업하고 있습니다.로그인 한 사용자에 대해 Google에 연결 (권한 부여)하는 Google

인증에서 우리는 백엔드와 프론트 엔드 간의 통신을 위해 JTW 토큰을 사용합니다. 토큰은 로컬 사용자 이름과 암호를 기반으로 생성됩니다.

이제 google 캘린더 API에 사용할 프로필에 사용자의 Google 계정을 '추가'(승인)하고 싶습니다. (this->https://github.com/wanasit/google-calendar을 사용)

이미 Google 인증 페이지로 사용자를 보내고 토큰을 다시 가져 왔습니다. 문제는 사용자가 페이지로 리다이렉트되면 사용자 요청을 확인하는 JWT 토큰을 잃어 버리는 것이다.

현재 로그인 한 사용자를 얻거나 authorize 메서드를 호출 할 때 일부 사용자 지정 콜백 권한 헤더/매개 변수를 전달하는 다른 방법이 있습니까?

auth.js :

var googleParams = { 
     clientID: config.auth.google.clientID, 
     clientSecret: config.auth.google.clientSecret, 
     callbackURL: config.auth.google.callbackURL 
    } 
    var googleStrategy = new GoogleStrategy(googleParams, function (token, refreshToken, profile, done) { 
     profile.token = token; 
     return done(null, profile); 
    }); 

경로 :

rotas.get(
    '/google', 
    auth.authenticate(), // will check the current user 
    auth.isLoggedIn, // make sure the user is really logged in 
    auth.authorize('google', { scope: googleScope, passReqToCallback: true }) // redirects to google to get the token 
); 

rotas.get('/callback/google', 
    auth.authorize('google', { scope: googleScope, passReqToCallback: true }) 
    auth.authRedirect() 
); 

auth.authRedirect() 기능은 위의 내가 찾은 가장 가까운 솔루션입니다. 그것은 사용자가 인증 된 프론트 엔드의 알려진 경로로 사용자를 리디렉션하는 Express 미들웨어입니다.하지만 필요한 모든 Google 프로필과 정보를 가져올 수는 없습니다 ...

답변

1

했다 :

  1. 는 사용자의 ID를 가져옵니다

  2. access_token은 JWT를 통해 요청하는 사용자를 인증하고 state 옵션의 속성에 설정

  3. 사용자가 Google 인증 페이지로 리디렉션되어 연결하려는 계정을 선택하십시오.

  4. (S) 그는 state 쿼리 PARAM 갖는 사용자의 ID 이제

  5. 난 그냥, 그 ID를 얻을 데이터베이스에서 사용자를 검색하고 내가 req.account에서 필요한 데이터를 설정해야 내 콜백 URL로 리디렉션됩니다 여기에는 사용자의 openid 프로필이 들어 있습니다.지금까지의 내가,```passport.authorize```과``알고`passport.authenticate```

var googleScope = ['openid', 'email', 'https://www.googleapis.com/auth/calendar']; 
 

 
routes.get(
 
    '/google', 
 
    auth.authenticate(), 
 
    auth.isLoggedIn, 
 
    function (req, res, next) { 
 
     var _id = '' + req.user._id; // convert to String... _id is an mongoose object 
 
     return auth.authorize('google', { session: false, scope: googleScope, passReqToCallback: true, state: _id })(req, res, next) 
 
    } 
 
); 
 

 
routes.get('/callback/google', 
 
    function (req, res, next) { 
 
     auth.authorize('google', { session: false, scope: googleScope, passReqToCallback: true })(req, res, next); 
 
    }, 
 
    auth.saveUserData() 
 
);

saveUserData= function() { 
 
    return function (req, res, next) { 
 
     if (req.query.state) { 
 
      var _id = req.query.state; 
 
      User.findOne({ _id, deleted: false, active: true }) 
 
       .exec(function (err, user) { 
 
        if (err) { 
 
         res.send(err); 
 
        } 
 
        if (user) { 
 
         user.auth.google = { 
 
          id: req.account.id, 
 
          token: req.account.token, 
 
          email: (req.account.emails.length ? req.account.emails[0].value : null), 
 
          name: req.account.displayName 
 
         } 
 
         user.save(function (err, data) { 
 
          if (err) { 
 
           res.send(err); 
 
          } else { 
 
           res.redirect('/') 
 
          } 
 
         }) 
 
        } else { 
 
         res.sendStatus(401); 
 
        } 
 
       }) 
 
     } else { 
 
      res.sendStatus(400) 
 
     } 
 
    }

+0

흠 ... 좋은! 나는이'국가'재산을 몰랐다. 잘 했어. –

1

어떤 경로보다 먼저 app.use(session)이 호출되었는지 확인하십시오.

...
app.use(session({ 
    secret: 'secret' 
})) 

app.use(passport.initialize()) 
app.use(passport.session()) 

... 

rotas.get(
    '/google', 
    auth.authenticate(), // will check the current user 
    auth.isLoggedIn, // make sure the user is really logged in 
    auth.authorize('google', { scope: googleScope, passReqToCallback: true }) // redirects to google to get the token 
); 

rotas.get('/callback/google', 
    auth.authorize('google', { scope: googleScope, passReqToCallback: true }) 
    auth.authRedirect() 
); 

당신의 req.user이 경우 undefined되지 않습니다.

올바른 방법으로 작동하지 않으면 여기에서 작성한 전체 코드를 넣을 수 있습니다.

희망이 당신을 도울 것입니다! :) 내가하고 결국 그래서

+0

은 거의 동일합니다 ... 차이점은'''authenticate''는'''req.user''와'''authorize''가''req.account''를 설정한다는 것입니다. 그것은 분명히 질문에,하지만 내가 정말로하려고하는 것은 그/그녀가 이미 가지고있는 자격 증명을 사용하여 사용자를 "재 인증"하는 것입니다. 콜백을 인증 할 수 있도록 일부 매개 변수를 전달하여 사용자를 얻고 " 로컬 사용자 프로필에 Google 데이터를 저장하는 계정을 승인 "합니다. –

+0

예, 시도했지만 Google에서 자동 응답을 요청한 사용자를 얻을 수 없습니다. 참고 : 사용자를 "로그인"하려고하지 않고 ... 로컬 프로필에 Google 계정을 연결하면 ... –

+0

프로필 데이터가 이미 있습니다. 맞습니까? 방금 로그인하여 프런트 엔드에 프로필 데이터를 보내고 싶습니다. 맞습니까? 일단 프로필 데이터 (그리고 Google의 jwt 토큰)를 얻으면 토큰을 사용하여 자신의 API에 액세스 할 수있는 권한을 부여 받기를 원합니다. 권리? –

관련 문제