NodeJS 混合passport-facebook和passport-jwt的最佳方式是什么?

isr3a4wc  于 11个月前  发布在  Node.js
关注(0)|答案(3)|浏览(103)

我是Node.js开发的新手,目前在空闲时间做一个宠物项目。
到目前为止,我已经使用passportpassport-jwt为策略创建了JWT身份验证,并且在我所有的RESTful API中使用它。
现在我正在考虑将其与某种Facebook身份验证混合使用,但我仍然希望坚持使用令牌身份验证。
目前,我是这样生成和获取代币的:

exports.authenticate = function(req, res) {
    User.findOne({
        email: req.body.email
    }, function(err, user) {
        if (err)
            return res.status(400).send(getErrorMessage(err));

        if (!user) {
            res.status(400).send({
                success: false,
                message: 'Authentication failed. User not found.'
            });
        } else {
            if (user.checkPassword(req.body.password)) {

                let token = jwt.encode(user, config.secretPhrase);

                res.json({
                    success: true,
                    token: 'JWT ' + token
                });
            } else {
                res.status(401).send({
                    success: false,
                    message: 'Authentication failed. Wrong password.'
                });
            }
        }
    });
};

app.route('/api/users/authenticate')
        .post(user.authenticate);

字符串
为了验证,我做了以下事情:

let user = require('../../app/controllers/user-controller');
app.route('/api/todos')
        .get(user.validateLogin, todos.list)
        .post(user.validateLogin, todos.create);


用户控制器:

exports.validateLogin = passport.authenticate('jwt', {
    session: false
});


任何人都可以建议一个整洁的方式来混合这两种策略?我应该使用express-jwt吗?express-jwt和passport-jwt之间有什么区别?

e1xvtsh3

e1xvtsh31#

您可以像使用passport-jwt一样使用passport-facebook,并使用新策略,这样您就可以在数据库中保存Facebook用户令牌并返回令牌

flseospp

flseospp2#

看起来好像当前您正在将令牌发送回最终用户。您如何保存客户端?我建议使用简单的JWT库,如jsonwebtoken,并将令牌设置为httpOnly cookie。如果您当前将其保存在localStorage中,则可能更容易受到XSS攻击。以下是我当前如何处理用户的JWT设置和检查的要点:https://gist.github.com/briancw/8c2021817c3bd34972e8e8deb6048a4f

hs1ihplo

hs1ihplo3#

你可以先使用passport-jwt auth策略,然后在passport-facebook策略中将参数passReqToCallback: true传递给super(),并添加request作为validate函数的第一个参数,在该函数中,你现在可以合并facebook oauth响应和来自passport-jwt策略的req.user

import { Injectable } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';
import { Profile, Strategy } from 'passport-facebook';
import { PrismaService } from 'src/commons/services/prisma.service';
import { Request } from 'express';

@Injectable()
export class FacebookStrategy extends PassportStrategy(Strategy, 'facebook') {
  constructor() {
    super({
      // ...
      passReqToCallback: true,
    });
  }

  async validate(
    req: Request, // add this param
    accessToken: string,
    refreshToken: string,
    profile: Profile,
    done: (err: any, user: any, info?: any) => void,
  ): Promise<any> {
    const payload = {
      profile,
      accessToken,
      user: req.user, //combine strategies here
    };

    done(null, payload); // payload will be available as req.user
  }
}

字符串

相关问题