[英]Can I build my project with oauth2 in Node JS
I want to use oauth2 authorization and resource servers with nodejs in my project.我想在我的项目中使用带有 nodejs 的 oauth2 授权和资源服务器。 But I could not that.但我不能那样做。 I tried many times to build oauth2 server with oauth2orize, express-oauth-server, oauth2-server libs but does not work.我尝试了很多次使用oauth2orize、express-oauth-server、oauth2-server库构建 oauth2 服务器,但不起作用。 Please help me to build my proejct with oauth2请帮助我用 oauth2 构建我的项目
see my blog at http://authguidance.com在http://authguidance.com 上查看我的博客
NodeJS + tutorial based - with code samples and write ups基于 NodeJS + 教程 - 带有代码示例和文章
And you can send me questions你可以给我发问题
Very detailed though - might make your brain hurt!!虽然非常详细 - 可能会让你的大脑受伤!!
You can use passportjs to provide you the oauth 2.0 support.您可以使用passportjs 为您提供oauth 2.0 支持。 You will need googleClientID and googleClientSecret.您将需要 googleClientID 和 googleClientSecret。 Which you can get by registering your application to google developers site您可以通过将您的应用程序注册到谷歌开发者网站来获得
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);
});
});
}
Dependencies = "passport": "^0.4.0", "passport-google-oauth": "^1.0.0"依赖项 = "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.