用护照处理未经授权的401

时间:2018-05-22 06:16:01

标签: node.js jwt passport.js

我有一个基于MEAN-Stack的应用程序,我使用护照来处理登录/注销等。

因此,当令牌现在无效并且用户单击我的应用程序内的链接时,他只会在控制台中获得“未授权”,如下所示: enter image description here

所以我想要的是调用一个函数来清除localStorage并将其重定向到登录页面,但我不知道我必须在哪里执行此操作。这是我的代码:

app.js

//Port Number
const port = 3000;

//CORS Middleware
app.use(cors());

//Set static folder
app.use(express.static(path.join(__dirname, 'public')));

// Body Parser Middleware
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ limit: '20mb', extended: false }));

//Passport Middleware
app.use(passport.initialize());
app.use(passport.session());
//Importing Authentication
require('./config/passport')(passport);

app.use('/users', users);
app.use('/terminalType', terminalType);
app.use('/customer', customer);
app.use('/terminal', terminal);
app.use('/stock', stock);
app.use('/logbook', logbook);
app.use('/partner', partner);
app.use('/userrights', userrights);
app.use('/activity', activity);
app.use('/activityRecord', activityRecord);
app.use('/customerContract', customerContract);
app.use('/queenBeeRaces', queenBeeRaces);
app.use('/beecolony', beecolony);
app.use('/beehiveTypes', beehiveTypes);
app.use('/bugTypes', bugTypes);
app.use('/visitReporting', visitReporting);

//Calling Index-Route
app.get('/', (req, res) => {
    res.send('Ungültige Route!');
});

app.get('*', (req, res) => {
    res.sendFile(path.join(__dirname, 'public/index.html'));
});

//Run server with nodemon
app.listen(port, () => {
    console.log('Server started on port '+port);
});

passport.js

const JwtStrategy = require('passport-jwt').Strategy;
const ExtractJwt = require('passport-jwt').ExtractJwt;
const User = require('../models/user');
const config = require('../config/database');

module.exports = function(passport) {
    let opts = {};
    opts.jwtFromRequest = ExtractJwt.fromAuthHeaderWithScheme("jwt");
    opts.secretOrKey = config.secret;
    passport.use(new JwtStrategy(opts, (jwt_payload, done) => {

        User.getUserById(jwt_payload.data.user._id, (err, user) => {
            if(err){
                return done(err, false);
            } 

            if(user){
                return done(null, user);
            } else {
                return done(null, false);
            }
        });
    }));
}

1 个答案:

答案 0 :(得分:1)

我认为您需要在Angular代码中执行此操作,因为用户将与之交互。您可以在Angular应用中查看HTTP 401,如果遇到问题,请使用localStorage清除localStorage.clear();并将用户重定向到登录页面。