未知的身份验证策略“ github”

时间:2018-11-05 10:11:12

标签: javascript express oauth passport.js github-api

GitHub的在线身份验证不起作用。我已经在GitHub上注册了新应用,但该应用仍不会重定向到OAuth。

我编写了以下代码,并得到错误:未知身份验证策略“ github”

const passport      = require('passport');
const bcrypt        = require('bcrypt');

module.exports = function (app, db) {

    app.route('/')
      .get((req, res) => { 
        res.render(process.cwd()+'/views/pug/index', {title: 'Hello', message: 'Please login',showLogin: true, showRegistration: true});
      });


    app.route('/login')
      .post(passport.authenticate('local',{ failureRedirect: '/' }),(req,res)=>{
         res.redirect('/profile');
      });

    function ensureAuthenticated(req, res, next) {
      if (req.isAuthenticated()) {
        return next();
      }
      res.redirect('/');
     }

    app.route('/profile')
      .get(ensureAuthenticated, (req,res) => {
         res.render(process.cwd() + '/views/pug/profile',{username:req.user.username});
      });

    app.route('/logout')
      .get((req, res) => {
        req.logout();
        res.redirect('/');
      });


    app.route('/register')
     .post((req, res, next) => {
        var hash = bcrypt.hashSync(req.body.password, 12);
        db.collection('users').findOne({ username: req.body.username }, function (err, user) {
          if(err) {
              next(err);
          } else if (user) {
              res.redirect('/');
          } else {
              db.collection('users').insertOne(
                {username: req.body.username,
                 password: hash},
                (err, doc) => {
                    if(err) {
                        res.redirect('/');
                    } else {
                        next(null, user);
                    }
                }
              )
          }
      })},
    passport.authenticate('local', { failureRedirect: '/' }),
    (req, res, next) => {
        res.redirect('/profile');
    }
    );

  /*GitHub OAuth*/

  app.route('/auth/github')
    .get(passport.authenticate('github'));

   app.route('/auth/github/callback')
    .get(passport.authenticate('github', { failureRedirect: '/' }), (req,res) => { 
    res.redirect('/profile'); 
  });

  /*End of GitHub OAuth*/

  app.use((req, res, next) => {
    res.status(404)
      .type('text')
      .send('Not Found');
  });
}

似乎我缺少OAuth的其他内容。我没有定义策略,我只是访问GitHub的默认策略。

1 个答案:

答案 0 :(得分:1)

您必须在脚本中配置护照github策略。 https://github.com/jaredhanson/passport-github var GitHubStrategy = require('passport-github')。Strategy;

passport.use(new GitHubStrategy({
    clientID: GITHUB_CLIENT_ID,
    clientSecret: GITHUB_CLIENT_SECRET,
    callbackURL: "http://127.0.0.1:3000/auth/github/callback"
  },
  function(accessToken, refreshToken, profile, cb) {
    User.findOrCreate({ githubId: profile.id }, function (err, user) {
      return cb(err, user);
    });
  }
));