node.js - 通过 LinkedIn 登录使用 Passport 对用户进行身份验证

标签 node.js express authentication linkedin-api passport.js

我在 Passport 中构建了一个登录系统并且运行得很好。现在,我想将 LinkedIn 登录集成到我的系统中。我已经有登录所需的 clientIDclientSecret 等。这是按下 LinkedIn 登录按钮时调用的代码。

passport.use('linkedin', new OAuth2Strategy({
    authorizationURL: 'https://www.linkedin.com/uas/oauth2/authorization',
    tokenURL: 'https://www.linkedin.com/uas/oauth2/accessToken',
    clientID: clientid,
    clientSecret: clientsecret,
    callbackURL: '/linkedinLogin/linkedinCallbackUrlLogin',
    passReqToCallback: true
},
function(req,accessToken, refreshToken, profile, done) {
    console.log('authenticated');
    console.log(accessToken);
    req.session.code = accessToken;
    process.nextTick(function () {
        done(null, {
            code : req.code
        });
    });
}));

回调函数中的两个 console.log() 调用均已成功触发,这意味着我已通过 LinkedIn 成功登录,并且收到了我的访问 token 。因此,我与 LinkedIn 连接的部分是正确的,我缺少的是我实际登录用户的部分。如您所见,callbackURL 指向/linkedinLogin/linkedinCallbackUrlLogin。这就是我在该 route 所做的:

app.get('/linkedinLogin/linkedinCallbackUrlLogin', passport.authenticate('linkedin', {
    session: false,
    successRedirect:'/linkedinLogin/success',
    failureRedirect:'/linkedinLogin/fail'
}));

我只是指定一个 successRedirect 和一个 failureRedirect。请注意,如果我输入 session : true,我会收到错误 Failed to serialize user into session,所以现在我将其保留为 false。

成功调用successRedirect。在该路由中,我向 LinkedIn 调用 GET 请求来访问有关用户的一些数据。我想将此数据存储在我的数据库中并记住登录的用户。这就是我的做法:

https.get(
    {
    host: 'api.linkedin.com' ,
    path: '/v1/people/~?format=json' ,
    port:443 ,
    headers : {'Authorization': ' Bearer ' + req.session.code}
    },
    function(myres) {
        myres.on("data", function(chunk) {
            var linkedinJsonResult = JSON.parse(chunk);
            User.findOne({linkedinLogin : linkedinJsonResult.id}, function(err, userSearchResult){
                if(err) {
                    throw err;
                }

                //user found, login
                if(userSearchResult){
                    console.log(userSearchResult);
                }
                else {
                    //create user
                    var newUser = new User(
                        {
                            url : linkedinJsonResult.siteStandardProfileRequest.url,
                            name : linkedinJsonResult.firstName + " " + linkedinJsonResult.lastName,
                            linkedinLogin : linkedinJsonResult.id,
                            regDate : new Date()
                        }
                    );

                    //save user
                    newUser.save(function(err, user){
                        if(err){
                            throw err;
                        }

                        //login
                        console.log(user);
                    });
                }

            });
    });
    }
);

让我解释一下那里的代码。获取用户的数据后,我检查收到的“id”字段。如果此 ID 与存储到数据库中的某个用户的 linkedinLogin 字段匹配,我认为它已经注册(已在数据库中找到该用户),因此我必须让他/她登录。否则我只是使用从 GET 请求接收到的数据创建一个新用户。

我的问题是,在这两种情况下 - 在我的数据库中找到用户,或者必须创建用户 - 每当与交互时如何将 req.user 设置为我的用户我的网站?仅执行 req.user = userSearchResult (如果在 if 语句内找到用户)或 req.user = user 就足够了(如果用户已在 newUser.save() 回调中创建),或者我应该调用一些 Passport 函数来为我设置它?

与用户注册和登录相关的所有其他 Passport 功能(无需使用 LinkedIn 登录)均工作正常。我只是担心如何让 LinkedIn 登录与 Passport 一起使用。

谢谢。

最佳答案

passport.js 会自动将 req.user 对象设置为您将作为第二个参数传递给策略回调的 done 函数的对象。

这意味着你应该这样做:

function(req,accessToken, refreshToken, profile, done) {
    console.log('authenticated');
    console.log(accessToken);
    req.session.code = accessToken;
    process.nextTick(function () {
        // retrieve your user here
        getOrCreateUser(profile, function(err, user){
            if(err) return done(err);
            done(null, user);
        })

    });
}));

我希望这会有所帮助。

关于node.js - 通过 LinkedIn 登录使用 Passport 对用户进行身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34738225/

相关文章:

javascript - Node+Express 发布错误

node.js - 如何从express/node应用程序在 ".localhost"上设置cookie,以便可以从 "something.localhost"访问它

asp.net - 制作安全登录cookie

node.js - Strapi 上传插件 - 如何放置由 Strapi 后端 js 代码生成的文件

node.js - Grunt 服务器在 Nitrous.io 中无法工作

node.js - API token 在 Flux (Redux) 存储中安全吗?

node.js - 迁移 knex : storing media, 图像或 blob 中的表

node.js - Sails.js API Passport.js 身份验证

python - 如何使用 python 的 urllib2 库仅请求一次而不是两次身份验证 url

node.js - heroku pkg-config 安装失败