0
我也跟着下面的文件,並試圖安裝谷歌的OAuth我的應用程序的NodeJS:https://cloud.google.com/nodejs/getting-started/authenticate-users節點JS護照谷歌的OAuth不進行身份驗證
我oauth2.js代碼如下:
const express = require('express');
const passport = require('passport');
const GoogleStrategy = require('passport-google-oauth20').Strategy;
function extractProfile (profile) {
let imageUrl = '';
if (profile.photos && profile.photos.length) {
imageUrl = profile.photos[0].value;
}
return {
id: profile.id,
displayName: profile.displayName,
image: imageUrl
};
}
passport.use(new GoogleStrategy({
clientID: <CLIENT ID as string>,
clientSecret: <CLIENT SECRET as string>,
callbackURL: 'http://<APP DOMAIN>/auth/google/callback'
}, (accessToken, refreshToken, profile, cb) => {
cb(null, extractProfile(profile));
}));
passport.serializeUser((user, cb) => {
cb(null, user);
});
passport.deserializeUser((obj, cb) => {
cb(null, obj);
});
const router = express.Router();
function authRequired(req, res, next){
if(!req.user){
req.session.oauth2return = req.originalUrl;
return res.redirect('/auth/login');
}
next();
}
function addTemplateVariables(req, res, next){
res.locals.profile = req.user;
res.locals.login = `/auth/login?return=${encodeURIComponent(req.originalUrl)}`;
res.locals.logout = `/auth/logout?return=${encodeURIComponent(req.originalUrl)}`;
next();
}
router.get(
'/auth/login',
(req, res, next) => {
if(req.query.return) {
req.session.oauth2return = req.query.return;
}
next();
},
passport.authenticate('google', {scope: ['email', 'profile']})
);
router.get('/auth/google/callback',
passport.authenticate('google', {
successRedirect: '/index',
failureRedirect: '/'
})
);
router.get('/auth/logout', (req, res)=>{
req.logout();
res.redirect('/');
});
module.exports = {
extractProfile: extractProfile,
router: router,
required: authRequired,
template: addTemplateVariables
};
而且似乎像其他一切工作正常。我被重定向到Google OAuth許可屏幕,並且在登錄後,我應該選擇允許(授予權限)。 但是,當我重定向到/ auth/google/callback時, passport.authenticate('google' ...
部件未進行身份驗證,並且出現404 Not Found錯誤(不是GET錯誤)。
我知道重定向是否正常工作,因爲如果我嘗試
router.get('/auth/google/callback',
function(req, res){
res.redirect('/index');
}
);
應用重定向沒有問題。
我該怎麼辦?我猜這是與令牌有關,但我不知道要檢查/修復什麼。
非常感謝你提前。