passport-jwt总是返回' Unauthorized' - 401

时间:2017-12-05 11:35:53

标签: javascript express authentication jwt passport.js

我试图在我的应用程序中执行社交认证,为此我使用两个模块:passport-google-oauth-20和passport-jwt。

当用户成功使用Google帐户登录时,我会创建一个令牌并将其作为持有人令牌发送到标头,其中包含“授权”功能。标题类型。

问题是:当我尝试访问某些受保护的路由时,始终返回未经授权的路由。看起来像passport.authenicate(' jwt')没有被调用。

这是我的代码:

const express = require('express')
const JwtStrategy = require('passport-jwt').Strategy
const ExtractJwt = require('passport-jwt').ExtractJwt
const GoogleStrategy = require('passport-google-oauth20').Strategy
const passport = require('passport')
const morgan = require('morgan')
const moment = require('moment')
const db = require('./configs/database')
const User = require('./models/user')
const PORT = (process.env.PORT || 8080)
const jwt = require('jsonwebtoken')
const app = express()

app.set(db)
app.use(morgan('dev'))
app.use(function(req, res, next) {  
    res.header("Access-Control-Allow-Origin", "*");
    res.header('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTIONS');
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization, Access-Control-Allow-Credentials");
    res.header("Access-Control-Allow-Credentials", "true");
    next();
  });




//passport setup
let opts = {}
opts.jwtFromRequest = ExtractJwt.fromAuthHeaderAsBearerToken()
opts.secretOrKey = 'shhhhhhhhhhhh'

passport.use('jwt', new JwtStrategy(opts, function(jwt_payload, done){
    User.findById(jwt_payload.user._id, (err, user)=>{
        if(user){
            return done(null, user)
        } else{
             return done(null, false)
        }
        if(err){
            return done(err, false)
        }
    })
}))

passport.use(new GoogleStrategy({
    clientID: '',
    clientSecret: '',
    callbackURL: "http://localhost:8080/auth/google/callback"
  },
  function(accessToken, refreshToken, profile, cb) {

    User.findOne({'google.id': profile.id }, function (err, user) {
        if(user){
            return cb(null, user)
        }
        else{
            let newUser = {
                'google.id':profile.id,
                'google.name':profile.displayName,
                'google.token':accessToken
            }
            User.create(newUser, (err, user)=>{
                return cb(null, user)
            })
        }
        if(err){
            return cb(err)
        }
    });
  }
));


app.get('/auth/google',
passport.authenticate('google', { scope: ['profile','email'] }));


app.get('/auth/google/callback', 
passport.authenticate('google', { failureRedirect: '/login', session:false}),
    (req, res) => {
    console.log(req.user._id)
    let token = jwt.sign({id:req.user._id, user:req.user, sucess:true}, 'shhhh',{expiresIn:36000})
    res.json({token:'Bearer ' + token})
});


app.get('/dashboard', passport.authenticate('jwt', { session: false }), function(req, res) {  
    res.json({message:'worked', user:req.user})
  });



app.listen(PORT, () => {
    console.log(`Server running on PORT ${PORT}. At: ${moment().format('LT')}`)
})

1 个答案:

答案 0 :(得分:1)

像我最近所做的那样,为将来遇到的其他人添加一个,您必须初始化护照:

  

在基于Connect或Express的应用程序中,需要使用password.initialize()中间件来初始化Passport。如果您的应用程序使用持久性登录会话,则还必须使用password.session()中间件。

http://www.passportjs.org/docs/configure/