Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nuxt auth with passportjs?

How use nuxt auth Module (front-end) with passport-local using JWT (back-end express) ?

defining jwt strategy for verify jwt token (express)

    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
            }
        });
    }));

defining local strategy for verify username nad password (express)

    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);
        });
      }
    ));

code for issuing token after verifying username and password (expresss)

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

nuxt auth local strategy consume username and passsword returns a JWT token (nuxt)

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

It can work independently how do i combine these ?

like image 620
PRAJIN PRAKASH Avatar asked Feb 27 '20 13:02

PRAJIN PRAKASH


1 Answers

code for express

Create passport strategies

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);
        });
    })
);

use passport strategies

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');
        }
    });
}
);

configuration for nuxt

inside 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'
      }
}

inside Login .vue

    this.$auth
      .loginWith('local', {
        data: {
          username: this.user.email,
          password: this.user.password
        }
      })
      .catch(err => {
        console.error(err );
      });
like image 85
PRAJIN PRAKASH Avatar answered Oct 29 '22 17:10

PRAJIN PRAKASH