2012-03-27 3 views
17

저는 Express 및 Passport OpenID Google 전략을 사용하고 있으며 각 인증 요청마다 returnURL을 설정하여 해당 인증을 시작한 페이지로 돌아갈 수 있습니다.Node.js의 맞춤 returnUrl Passport의 Google 전략

상황은 내가 Node.js 백엔드 (및 소셜 콘텐츠와 편집기 및 포털 및 확장 ... https://github.com/bubersson/humla)로 HTML5 슬라이드 응용 프로그램을 가지고 있으며 슬라이드 메뉴를 통해 일부 슬라이드에서 사용자로 로그인 할 수 있기를 원합니다. ...)하지만 그 사람이 같은 슬라이드로 쉽게 돌아 오기를 바란다.

그래서 나는 이렇게 할 필요가 있을까요?

app.get('/auth/google', function(req,res) { 
    var cust = "http://localhost:1338/"+req.params.xxx; 
    passport.authenticate('google', returnURL:cust, function ... 
} 

여권 가이드를 읽었지만 그 방법을 아직 모릅니다. 나는 이것이 안전하지 않을 것이라는 것을 안다, 그러나 나는 어떻게 그것을 할 수 있 었는가?

또는 로그인을 시작한 페이지로 돌아가려면 어떻게 응용 프로그램을 만들 수 있습니까? 아니면 AJAX를 사용하여 OpenID 인증을 만드는 방법이 있습니까? (여전히 여권을 사용할 수 있습니까?)

답변

24

에 대한 콜백에서 res.redirect('back');을 시도, 나는 GoogleStrategy이 매우 유사하다는 것을 확신합니다.

당신이 (여권 가이드에서)과 같이 인증 서비스에서 콜백에 대한 경로를 정의 가정 :

app.get('/auth/twitter/callback', 
    passport.authenticate('twitter', { 
     successRedirect: authenticationRedirect(req, '/account') 
    , failureRedirect: '/' 
    }) 
); 

그냥이 해당 블록을 변경 :

app.get('/auth/twitter/callback', function(req, res, next){ 
    passport.authenticate('twitter', function(err, user, info){ 
    // This is the default destination upon successful login. 
    var redirectUrl = '/account'; 

    if (err) { return next(err); } 
    if (!user) { return res.redirect('/'); } 

    // If we have previously stored a redirectUrl, use that, 
    // otherwise, use the default. 
    if (req.session.redirectUrl) { 
     redirectUrl = req.session.redirectUrl; 
     req.session.redirectUrl = null; 
    } 
    req.logIn(user, function(err){ 
     if (err) { return next(err); } 
    }); 
    res.redirect(redirectUrl); 
    })(req, res, next); 
}); 
이의 변형을 시도

자,이 같은 세션에서 원래의 URL을 저장하는 인증 경로에 대한 귀하의 미들웨어를 정의

ensureAuthenticated = function (req, res, next) { 
    if (req.isAuthenticated()) { return next(); } 

    // If the user is not authenticated, then we will start the authentication 
    // process. Before we do, let's store this originally requested URL in the 
    // session so we know where to return the user later. 

    req.session.redirectUrl = req.url; 

    // Resume normal authentication... 

    logger.info('User is not authenticated.'); 
    req.flash("warn", "You must be logged-in to do that."); 
    res.redirect('/'); 
} 

작동!

+0

완벽하게 작동하지만 리디렉션시 사용자가 인증되어 다시 돌아 오기 위해 보낸 경우 해시 매개 변수가 누락 된 것으로 보입니다. 로그인 후 리디렉션 할 때 해당 URL을 URL에 보관할 수있는 방법이 있습니까? http://stackoverflow.com/questions/14124932/passport-js-express-js-forward-user-to-original-destination-after-authenticati – prototype

+0

@ user645715 아마도'req.session.redirectUrl = req.originalUrl을 사용해보십시오. ; 대신'req.url' –

+0

은 매력처럼 작동합니다. 감사합니다 :) – Zub

5

이 내 애플 리케이션 트위터 인증이 알아 냈어요 passport.authenticate

+0

하 감사합니다! 분명히 첫 번째 및 두 번째 OpenID 요청 사이에 다시 경로가 설정됩니다. 나는 그것을 몰랐다! 감사합니다 – bubersson

+2

글쎄,이 문제가 발견. 이미 Google을 사용하여 로그인 한 경우에만 작동합니다. 여권이 Google 페이지로 리디렉션되어 내 사이트로 돌아 오면 "페이지"경로가 손실됩니다. 다른 방법으로 Google에서 내 위치 (로그인이 시작된 페이지)로 돌아갈 수 있습니까? – bubersson

+0

@bubersson 당신은 첫 번째 대답과 같은보다 능동적 인 접근법을 사용해야합니다. – matanster

3

저자에 따르면 이것은 OpenID 전략으로는 불가능합니다. 우리는 직접 변수에 액세스하여 동적으로 이러한 업데이트 관리 : 당신이 당신의 로그인 버튼이 어디

app.get('/auth/google', function(req, res, next) { 
    passport._strategies['google']._relyingParty.returnUrl = 'http://localhost:3000/test'; 
    passport._strategies['google']._relyingParty.realm = 'http://localhost:3000'; 
    passport.authenticate('google')(req, res, next); 
}); 
13

가하는 쿼리 매개 변수로 요청의 현재 URL을 추가을 (당신이 사용하는 어떤 템플릿 시스템 조정) :

<a href='/auth/google?redirect=<%= req.url %>'>Log In</a> 

그런 다음, req.session에이 값을 저장하는 당신의 GET /auth/google 핸들러에 미들웨어를 추가

app.get('/auth/google', function(req, res, next) { 
    req.session.redirect = req.query.redirect; 
    next(); 
}, passport.authenticate('google')); 

마지막으로, 콜백 핸들러에 세션에 저장되어있는 URL로 리디렉션 :

app.get('/auth/google/callback', passport.authenticate('google', 
    failureRedirect: '/' 
), function (req, res) { 
    res.redirect(req.session.redirect || '/'); 
    delete req.session.redirect; 
}); 
+0

세션없이이 작업을 수행 할 수 있습니까? – nahtnam