2014-07-22 3 views
4

Strongloop의 루프백 프레임 워크로 API 빌드를 보호하기 위해 passport.js + passport-facebook-token을 사용하고 있습니다.각 요청마다 passport.serializeUser가 실행되는 이유는 무엇입니까?

deserialize 된 사용자가 deserialize 된 후 Passport가 다시 serialize하는 이유는 무엇입니까? 또한 모든 요청에 ​​대해 passport.authenticate 메소드가 호출됩니다! 내가 도대체 ​​뭘 잘못하고있는 겁니까? 여기

deserializeUser, id: XXXXXXXXXXXXXXXX 
User found. 
serializeUser, id: XXXXXXXXXXXXXXXX 
GET /api/events?access_token=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX 304 182ms 

는 JS 코드 : 여기

노드의 로그 당신이 미들웨어로 정의하기 때문에 passport.authenticate이 모든 요청에서 호출 이유에 대한 질문에 대해서는

passport.use(new FacebookTokenStrategy({ 
    clientID: XXXXXXXXXXXXXXXX, 
    clientSecret: 'XXXXXXXXXXXXXXXXXXXXXXXXXXXX' 
    }, 
    function(accessToken, refreshToken, profile, done) { 
    //check user table for anyone with a facebook ID of profile.id 
    User.findOne({ 
     'facebookId': profile.id 
    }, function(err, user) { 
     if (err) { 
     return done(err); 
     } 
     if (user) { 
     console.log("User found."); 
     return done(err, user); 
     } else { 
     console.log("User not found."); 
     User.create({ 
      email: profile.emails[0].value, 
      facebookId: profile.id, 
      password: 'secret' 
     }, function(err, user) { 
      console.log(user.id); 
      console.log(user.email); 
      console.log(user.facebookId); 
      console.log("User created"); 
      return done(err, user); 
     }); 
     } 
    }); 
    })); 

passport.serializeUser(function(user, done) { 
    console.log('serializeUser, id: ' + user.facebookId); 
    done(null, user.facebookId); 
}); 

passport.deserializeUser(function(id, done) { 
    console.log('deserializeUser, id: ' + id); 
    User.findOne({ 
    'facebookId': id 
    }, function(err, user) { 
    if (!err) { 
     done(null, user); 
    } else { 
     done(err, user); 
    } 
    }); 
}); 
+1

인증을 처리하는 미들웨어를 정의하는 코드를 표시 할 수 있습니까? 'passport.authenticate ("facebook", function ....)'와 같이 보일 것입니다. 'app.get ("/ *", passport.authenticate())'와 같이하면 예상대로 작동합니다. –

+0

이 위치에 추가 된 유일한 위치는 다음과 같습니다. app.use (passport.authenticate ('facebook-token')); –

+0

흠, 알았어. 하지만 내 이해는 그것이 무단 액세스로부터 내 API를 보호하고 있기 때문에 그것이 미들웨어로 추가되어야한다는 것이 었습니다 ... 어디에이 라인을 추가 할 수있는 적절한 장소가 될 것입니까? 또는 무엇을 제안합니까? –

답변

7

, 그것은이다 아마도 라우팅 로직이 발생하기 전에. 지금

// Define a specific that will handle authentication logic 
app.get("/auth", passport.authenticate('facebook-token',function(){...}); 

// Public sections which do not require authentication 
app.get("/public1",...); 
app.post("/public2",...); 

// Private sections which do require authentication 
app.get("/private1", function(req,res,next){ 
    if (req.isAuthenticated()){ // Check if user is authenticated 
     // do things... 
    }else{ // Wow, this guy is not authenticated. Kick him out of here ! 
     res.redirect("/auth"); 
    } 
}); 

여러 민간 부분이있는 경우, 당신은 아마로가 조금 tidious 확인할 수있는 것들 : 앱에 개인 공공 부분이있는 경우

, 당신은 그런 일을 할 수 각 개인 섹션에 대해 동일한 작업을 수행하십시오. 사용자가 인증되었는지 확인하고 요청이있는 경우 요청을 진행할 수있는 사용자 지정 함수를 정의 할 수 있습니다. 이 같은

function isThisGuyAuthenticated(req,res,next){ 
    if (req.isAuthenticated()){ 
     return next(); // Ok this guy is clean, please go on ! 
    }else{ 
     res.redirect("/auth"); // This guy is shady, please authenticate ! 
    } 
} 

그리고 사용과 같은 뭔가 : 앱이 유일한 민간 부분이있는 경우

app.get("/private1",isThisGuyAuthenticated, doCrazySecretStuff); // doCrazySecretStuff will not be called if the user is not authenticated 
app.get("/private2", isThisGuyAuthenticated, getCocaColaRecipe); 
app.get("/private3", isThisGuyAuthenticated, flyToMars); 
app.get("/public", showInfo); // showInfo will be called whether the user is authenticated or not 

이제, 당신이 passport.authenticate을 정의하여 미들웨어로 정의하여 isThisGuyAuthenticated에 대한 호출을 반복 (그러나 피할 수 미들웨어로서의 자체!);

// Endpoint that will be hit is the user is redirected to /auth 
// BEWARE it needs to be above the middleware, otherwise you'll end up with an infinite redirection loop 
app.get("/auth", passport.authenticate('facebook-token',function(){...}); 

// Middleware that will be called on every request 
app.use(isThisGuyAuthenticated); 

// You app's endpoints 
app.get("/private1", doCrazySecretStuff); // doCrazySecretStuff will not be called if the user is not authenticated 
app.get("/private2", getCocaColaRecipe); 
app.get("/private3", flyToMars); 

분명합니까?

EDIT : 나는 실수로 "/ auth"엔드 포인트 앞에 미들웨어를 넣습니다. 배치 후 확인하십시오

+0

아주 좋은 답변입니다! 고마워, 많이 생각해, 지금은 분명해, 내 시도해보고 대답으로 확인해 보자! –

+1

반갑습니다. 문제가 있으면 알려주세요. 그리고 제 편집을 확인해주십시오. 처음에는 큰 실수가있었습니다. –

+0

정확히. 그리고/auth 함수에서 작은 오타가 수정되었습니다 ...! 그러나 그것은 효과적이다. 이제/auth에 대한 첫 번째 요청 만 다른 요청을 ~ 200ms 소요하고 기존 세션을 활용하며 매우 빠릅니다 (<10ms). THX –

관련 문제