简体   繁体   English

使用passport.js访问用户

[英]Access user using passport.js

I am using passport.js with the user strategy, when I console log req in my callback route I am getting the following part: 我在用户策略中使用passport.js,当我在回调路由中控制台日志请求时,得到以下部分:

sessionStore: MemoryStore {
  _events: [Object: null prototype] {
    disconnect: [Function: ondisconnect],
    connect: [Function: onconnect]
  },
  _eventsCount: 2,
  _maxListeners: undefined,
  sessions: [Object: null prototype] {
    'ssoT3fMSsf-d4xU9D0-SQPCaqOczzi_0': `{"cookie":{"originalMaxAge":null,"expires":null,"secure":false,"httpOnly":true,"domain":"localhost","path":"/"},"passport":{"user":...`
  },
  generate: [Function]
},
sessionID: 'CyGF1bCHjA6yvdC4MFxMt0Msj5zc1624',
session: Session {
  cookie: {
    path: '/',
    _expires: null,
    originalMaxAge: null,
    httpOnly: true,
    domain: 'localhost',
    secure: false
  }
},
_passport: {
  instance: Authenticator {
    _key: 'passport',
    _strategies: [Object],
    _serializers: [Array],
    _deserializers: [Array],
    _infoTransformers: [],
    _framework: [Object],
    _userProperty: 'user',
    _sm: [SessionManager],
    Authenticator: [Function: Authenticator],
    Passport: [Function: Authenticator],
    Strategy: [Function],
    strategies: [Object]
  }

My question is how can I send back the user? 我的问题是如何发回用户? I tried 我试过了

passport.use(
  new Strategy(
    {
      clientID: process.env.CLIENT_ID!,
      clientSecret: process.env.CLIENT_SECRET!,
      callbackURL: process.env.CALLBACK_URL,
      scope: ["identify", "guilds"],
    },
    (_, __, profile, cb) => cb(null, profile)
  )
)

passport.serializeUser((id, done) => {
  done(null, id)
})

passport.deserializeUser((id, done) => {
  done(null, id)
})

return res.send({ user: req.session.passport.user })

but without success, I am just not sure how to access the user but it is there 但是没有成功,我只是不确定如何访问用户,但是它在那里

One way I tried to get user is through serialization and deserialization methods. 我尝试获取用户的一种方法是通过序列化和反序列化方法。 You can read more about from here 您可以从这里了解更多信息

const express=require('express');
const expressSsn=require('express-session');
const bodyparser = require('body-parser');
const app= express();
const passport = require('passport');
const localstrategy = require('passport-Local').Strategy;
const user =require("../passport-demo/user");

app.use(bodyparser.json());
app.use(expressSsn({
secret : 'ok',
saveUninitialized : false,
resave : true,
}));

app.use(passport.initialize());
app.use(passport.session());

passport.serializeUser(function(usr,done){
   console.log("Serialized method");
   done(null,usr.token);
});

passport.deserializeUser(function(usr,done){

console.log("Deserialized method");
if(usr==user.token)
{
    console.log("Get Called  = ");
    done(null,user);
}
else
{
    console.log("Token not matched");
    done(null,false);
}
});

passport.use(new localstrategy(
{
    usernameField : 'username',
    passwordField : 'password'
},
function(username,password,done)
{
        if(username == user.username && password == user.password)
        {
            console.log("Correct Password");
            return done(null,user,{message : 'correct Password' });
        }
        else
        {
            console.log("Incorrect Password");
            return done(null,false);
        }
}
));

app.post('/',function(req,res,err)
{
   console.log(user);
   res.end();
});

app.post('/login',passport.authenticate('local')
   ,function (req,res,err)
   {
            res.send("Request : "+req.user.username);
});

app.post('/data',function(req,res,err)
{
  console.log(req.user);
  res.end();
});


app.listen(3000,console.log('host is running at 3000'));

As per passportjs documentations : 根据passportjs文档:

By default, if authentication fails, Passport will respond with a 401 Unauthorized status, and any additional route handlers will not be invoked. 默认情况下,如果身份验证失败,Passport将以401 Unauthorized状态响应,并且不会调用任何其他路由处理程序。 If authentication succeeds, the next handler will be invoked and the req.user property will be set to the authenticated user. 如果身份验证成功,则将调用下一个处理程序,并将req.user属性设置为已身份验证的用户。

So you can get the user as req.user 这样您就可以将用户作为req.user

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM