oauth2-server实现nodejs

时间:2018-01-02 10:04:58

标签: javascript node.js oauth-2.0 oauth2orize

我试图在nodeJS中实现OAUTH2服务器,它允许客户端应用程序使用我的网站登录用户(例如使用谷歌登录,在我的情况下,它是amazon alexa,它使用此API /客户端应用程序)。
我尝试使用oauth2orise(https://www.npmjs.com/package/oauth2orize)并引用了几个链接: -


先谢谢。

3 个答案:

答案 0 :(得分:1)

enter image description here

这张图来自我学习React时的udemy教程。 (https://www.udemy.com/node-with-react-fullstack-web-development/)。

我不确定这个图是否涉及你所谈论的流程 所以,如果是这样,请告诉我。

答案 1 :(得分:1)

我从这个存储库得到了一个非常解释性的答案。

https://github.com/FrankHassanabad/Oauth2orizeRecipes

感谢。

答案 2 :(得分:1)

您可以使用passportjs为您提供oauth 2.0支持。您需要googleClientID和googleClientSecret。您可以通过将您的应用程序注册到谷歌开发者网站来获得

var GoogleStrategy = require('passport-google-oauth20').Strategy;

 const mongoose = require('mongoose');
 const keys = require('./keys');
 const User = mongoose.model('users');

module.exports = function(passport){
  passport.use(
new GoogleStrategy({
  clientID:keys.googleClientID,
  clientSecret:keys.googleClientSecret,
  callbackURL:'/auth/google/callback',
  proxy:true
},(accessToken,refreshToken,profile,done)=>{
//     console.log(accessToken);
//     console.log(profile);
  const image = profile.photos[0].value.substring(0,profile.photos[0].value.indexOf('?'));

  const newUser = {
    googleID:profile.id,
    firstName:profile.name.givenName,
    lastName :profile.name.familyName,
    email:profile.emails[0].value,
    image:image
  }

  //Check for existing user
  User.findOne({
    googleID:profile.id
  }).then(user=>{
    if(user){
      //Return user
      done(null,user);
    }
    else{
      //Create a new user
      new User(newUser)
      .save()
      .then(user=> done(null,user)); 
    }
  })
 })
)

passport.serializeUser(function(user, done) {
done(null, user.id);
});

passport.deserializeUser(function(id, done) {
 User.findById(id, function(err, user) {
   done(err, user);
     });
   });
 }
  

依赖关系=“护照”:“^ 0.4.0”,       “passport-google-oauth”:“^ 1.0.0”

This will redirect req. to above code..
const express = require('express');
const router = express.Router();
const passport = require('passport');

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

 router.get('/google/callback', 
   passport.authenticate('google', { failureRedirect: '/' }),
   function(req, res) {
   // Successful authentication, redirect home.
   res.redirect('/dashboard');
  });

   router.get('/verify',(req,res)=>{
   if(req.user){
   console.log(req.user);
  }else{
   console.log('Not Auth');
  }
});

router.get('/logout',(req,res)=>{
   req.logout();
   res.redirect('/');
 })
 module.exports = router;