[英]How to secure Angular 4 routes using Passport JS?
我打算使用Node JS
, Express JS
和Passport JS
設置Google登錄。 在此過程中,我已使用應用程序憑據配置了Google策略,並創建了帶有登錄按鈕的示例.ejs
頁面,並且能夠登錄並檢索用戶個人資料。 后來,我刪除了示例頁面,並嘗試將所有靜態Angular 4文件(使用angular-cli構建)放置在Public
目錄中,並編寫了以下邏輯,
app.use(express.static(path.join(__dirname, 'public')));
app.get('/', function(req, res, next) {
if (req.isAuthenticated()) {
res.redirect("/home");; // Angular route
} else {
// require the user to log in
// redirects to Google Sign-in page
res.redirect("/auth/google");
}
});
現在,當我啟動服務器並訪問http://localhost:3000
,沒有看到任何重定向到Google登錄頁面的信息,而是瀏覽器直接呈現了http://localhost:3000/home
。
因此,我應該進行哪些更改以驗證用戶身份,然后將用戶重定向到主頁。 還要確保應用程序中的其他路由/子路由安全嗎?
if
要求有一個會話的簡單方法... app.get('/home', function(req, res) {
if(req.session){ //session exists (requesting user has a session)
// Angular route code goes here to prevent non-authed user access
}else{res.redirect("/");} //or res.redirect("/auth/google");
});
確保身份驗證
app.get('/home',
ensureLoggedIn('/auth/google'),
function(req, res) {
// Angular route code goes here to prevent non-authed user access
});
如果未對用戶進行/auth/google
,則請求將被重定向到/auth/google
,原始請求URL( /home
)將保存到會話中的req.session.returnTo。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.