簡體   English   中英

我可以在 Node JS 中使用 oauth2 構建我的項目嗎

[英]Can I build my project with oauth2 in Node JS

我想在我的項目中使用帶有 nodejs 的 oauth2 授權和資源服務器。 但我不能那樣做。 我嘗試了很多次使用oauth2orize、express-oauth-server、oauth2-server庫構建 oauth2 服務器,但不起作用。 請幫助我用 oauth2 構建我的項目

http://authguidance.com 上查看我的博客

基於 NodeJS + 教程 - 帶有代碼示例和文章

你可以給我發問題

雖然非常詳細 - 可能會讓你的大腦受傷!!

您可以使用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);
     });
   });
 }

依賴項 = "passport": "^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;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM