2017-01-16 83 views
8

將護照會話信息從後端發送到前端的最佳方式是什麼?Angular2的護照JS會話數據

我的應用程序在端口3000上工作。前兩個獲取用於Facebook登錄和重定向。接下來一個是從數據庫中獲取用戶數據(用戶ID應該存放在req.user

routes.js:

app.get('/auth/facebook', passport.authenticate('facebook', { scope : 'email' })); 

app.get('/auth/facebook/callback', 
     passport.authenticate('facebook', { 
      successRedirect : 'http://localhost:8000/', 
      failureRedirect : '/fail' 
     }) 
); 

app.get('/auth/userdata', isLoggedIn, function(req, res) { 
    Donator.findById(req.user, function(err, fulluser) { 
     if (err) throw err; 
     res.json(fulluser); 
    }) 
}); 

function isLoggedIn(req, res, next) { 
    if (req.isAuthenticated()) { 
     next(); 
    } else { 
     res.json(false); 
    } 
}; 

護照config.js

'facebookAuth' : { 
     'clientID'  : 'secret', 
     'clientSecret' : 'secret', 
     'callbackURL' : 'http://localhost:3000/auth/facebook/callback' 
    }, 

所以在我的Angular2應用我可以轉到http://localhost:3000/auth/facebook,重定向到FB登錄頁面,如果成功重定向到http://localhost:3000/auth/login/callback,那麼我將轉到http://localhost:8000/

而且在我Angular2的應用程序,在端口8000

getUser(){ 
    this.http.get('http://localhost:3000/auth/userdata') 
    .map(res => return res.json()) 
} 

每次getUser()作品被調用,它會返回 '假'。有沒有一種簡單而安全的方法可以將此會話數據「注入」我的前端的不同端口?另外,當我在瀏覽器中使用http://localhost:3000/auth/userdata時,我可以看到這個配置文件呈現爲JSON。

當我在同一端口上設置後端和前端它工作,臉譜,微博,谷歌,本地,一切都很好,getUser返回完整的用戶配置文件。

我希望它很清楚。

+0

你爲什麼不在端口'3000'上提供你的angular2應用程序? –

+1

我想讓前端在單獨的主機上結束後端。 – dmh126

+0

我建議在同一個端口上運行一切。您可以在不同端口上安裝兩臺服務器,但使用[express-http-proxy](https://www.npmjs.com/package/express-http-proxy)將其中一臺服務器代理到另一臺服務器。 –

回答

4

這是Angular2中的請求問題。我爲每個請求添加了憑據:

getUser(){ 
    this.http.get('http://localhost:3000/auth/userdata', {withCredentials: true}) 
    .map(res => return res.json()) 
} 

現在很好。

+0

嗨,我也加了{withCredentials:true}在我的請求,但得到首先cors問題,但然後添加res.header('訪問控制允許起源','http:// localhost:4200');在服務器中,我得到req.isAuthenticated()爲false。你如何解決這個問題? –

+0

我也有'res.header('訪問控制 - 允許 - 方法','GET,PUT,POST,DELETE,OPTIONS');'在我的cors選項中。它的工作,也爲POST請求,你應該包括像options = new RequestOptions({headers:headers,withCredentials:true})的選項' – dmh126