Nuxt auth 与passportjs?

Posted

技术标签:

【中文标题】Nuxt auth 与passportjs?【英文标题】:Nuxt auth with passportjs? 【发布时间】:2020-06-11 12:58:01 【问题描述】:

nuxt auth Module (front-end) 和 passport-local 如何使用 JWT (back-end express) ?

定义 jwt 策略以验证 jwt 令牌(快递)

    var JwtStrategy = require('passport-jwt').Strategy,
        ExtractJwt = require('passport-jwt').ExtractJwt;
    var opts = 
    opts.jwtFromRequest = ExtractJwt.fromAuthHeaderAsBearerToken();
    opts.secretOrKey = 'secret';
    opts.issuer = 'accounts.examplesoft.com';
    opts.audience = 'yoursite.net';
    passport.use(new JwtStrategy(opts, function(jwt_payload, done) 
        User.findOne(id: jwt_payload.sub, function(err, user) 
            if (err) 
                return done(err, false);
            
            if (user) 
                return done(null, user);
             else 
                return done(null, false);
                // or you could create a new account
            
        );
    ));

定义验证用户名和密码的本地策略(快速)

    passport.use(new LocalStrategy(
      function(username, password, done) 
        User.findOne( username: username , function (err, user) 
          if (err)  return done(err); 
          if (!user)  return done(null, false); 
          if (!user.verifyPassword(password))  return done(null, false); 
          return done(null, user);
        );
      
    ));

验证用户名和密码后颁发令牌的代码(快递)

    app.post('/login', 
      passport.authenticate('local',  failureRedirect: '/login' ), //need to update from nuxt auth.
      function(req, res) 
        res.redirect('/');
      );

nuxt auth 本地策略使用用户名和密码返回一个 JWT 令牌(nuxt)

    this.$auth.loginWith('local', 
      data: 
        username: 'your_username',
        password: 'your_password'
      
    )

它可以独立工作我如何结合这些?

【问题讨论】:

【参考方案1】:

快递代码

制定护照策略

const passport = require('passport');
const LocalStrategy = require('passport-local').Strategy;
const JwtStrategy = require('passport-jwt').Strategy;

passport.use(
    new LocalStrategy(
        
            usernameField: 'username',
            passwordField: 'password'
        ,
        function(username, password, done) 
            users.findOne( email: username , function(err, user) 
                if (err) 
                    return done(err);
                
                if (!user) 
                    return done(null, false,  error: 'Invalid username' );
                
                if (!user.checkPassword(password)) 
                    return done(null, false,  error: 'invalid password' );
                

                const info =  scope: '*' ;
                done(null, user, info);
            );
        
    )
);


const opts = ;
opts.jwtFromRequest = ExtractJwt.fromAuthHeaderAsBearerToken();
opts.secretOrKey = 'JWT_SECRET_OR_KEY';
passport.use(
    new JwtStrategy(opts, function(payload, done) 
        users.findById(payload, function(err, user) 
            if (err) 
                return done(err, false);
            
            if (user) 
                return done(null, user);
            
            return done(null, false);
        );
    )
);

使用护照策略

const express = require('express');
const passport = require('passport');
const app = express();
app.use(express.json());
app.use(express.urlencoded( extended: false ));
app.use(cookieParser());

app.use(passport.initialize()); // Used to initialize passport

// Routes

app.post(
        '/login',
        passport.authenticate('local',  session: false ),
        function(req, res) 
            const token = jwt.sign(req.user.userId, 'JWT_SECRET_OR_KEY');
            return res.json( token );
        
    );
app.get(
    '/me',
    passport.authenticate(['jwt', 'bearer'],  session: false ),
    function(req, res, next) 
    const  userId  = req.user;
    users.findOne( _id: userId , (err, data) => 
        if (err) 
            res.status(500).send(err);
         else if (data) 
            const userData = data;
            res.status(200).send(userData);
         else 
            res.status(500).send('invalid token');
        
    );

);

nuxt 的配置

在 nuxt.config.js 中

 auth: 
    resetOnError: true,
    redirect: 
      login: '/login', // User will be redirected to this path if login is required.
      home: '/app/dashboard', // User will be redirect to this path after login. (rewriteRedirects will rewrite this path)
      logout: '/login', // User will be redirected to this path if after logout, current route is protected.
      user: '/user/profile',
      callback: '/callback // User will be redirect to this path by the identity provider after login. (Should match configured Allowed Callback URLs (or similar setting) in your app/client with the identity provider)
    ,
    strategies: 
      local: 
        endpoints: 
          login: 
            url: '/login',
            method: 'post',
            propertyName: 'token'
          ,
          logout: false,
          user: 
            url: '/me',
            method: 'GET',
            propertyName: false
          
        ,
        tokenRequired: true,
        tokenType: 'Bearer'
      

在 Login .vue 中

    this.$auth
      .loginWith('local', 
        data: 
          username: this.user.email,
          password: this.user.password
        
      )
      .catch(err => 
        console.error(err );
      );

【讨论】:

点赞!如果您不使用 JWT,这是否有效,我的意思是如果您使用 express-session? 是的@PirateApp 你可能需要this

以上是关于Nuxt auth 与passportjs?的主要内容,如果未能解决你的问题,请参考以下文章

我正在尝试将 PassportJs 与多种类型的用户一起使用(每个用户都有不同的模型)。我究竟做错了啥?

PassportJs Google Auth2 failureRedirect 不起作用

PassportJs Google Auth 将现有用户保存为数据库中的新用户。我该如何解决?

如何设置PassportJS进行后端身份验证?

Nuxt-auth ..login 网络标头给了我奇怪的路径似乎是我登录页面的语言环境路径

Nuxt.js + Auth(jwt 刷新令牌)