How to add a users auth in feathers middleware?

寵の児 提交于 2020-12-14 12:06:19

问题


I use feathersjs framework in my projekt. In older version my middleware it was work but afer update a framework and after created new app with authenticate a middleware not working.

My index.js file show like below:

const cookieParser = require('cookie-parser');
const { authenticate } = require('@feathersjs/express');

module.exports = function (app) {

app.get('/login', (req, res) => {

    res.sender('login');
    
});

app.use('/', cookieParser(), authenticate('jwt'), async (req, res) => {

    const { user } = req;

    try {
        
        await app.service('users').get(user._id);
        
        res.sender('home');
        
    } catch(e){
        
        res.redirect('/login');
        
    }
    
});

}

I have a login script in jQuery like below:

$(document).ready(function(){

const socket = io();

const app = feathers();

app.configure(feathers.socketio(socket));

app.configure(feathers.authentication({
  storage: window.localStorage
}));

$('.form-signin').submit(function(){
    
    app.authenticate({
        strategy: 'local',
        username: $('#inputUsername').val(),
        password: $('#inputPassword').val(),
        
    }).then( result => {

        document.cookie = "feathers-jwt=" + result.accessToken;
        window.location.href = "/";
        
    }).catch(error => {});
  
  });
  
});

My problem is when I click a login button with a data correctly I receive an accessToken but I can't see home page and app show me every time 401 error code - not authorization with.

An console shows me this info: info: Invalid authentication information (no `strategy` set) {"type":"FeathersError","name":"NotAuthenticated","code":401,"className":"not-authenticated","errors":{}}

In new version not working too failureRedirect: '/login'

SOLUTION

Add below code before app.get('/', authenticate('jwt'), (req, res) => {});

app.use('/', cookieParser(), (req, res, next) => {
      
      var cookies = req.cookies;
      var token = cookies['feathers-jwt'];
      
      req.authentication = {
              strategy: 'jwt',
              accessToken: token
            }
      
      next();
  })

来源:https://stackoverflow.com/questions/63546227/how-to-add-a-users-auth-in-feathers-middleware

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!