sessionStorage中的Jwt验证在后端做出反应 [英] Jwt validation in sessionStorage react in backend

查看:253
本文介绍了sessionStorage中的Jwt验证在后端做出反应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个用于登录并生成JWT的api 运行正常,我将jwt保存在sessionStorage中:

I have an api that I consume to login and generate a JWT operating normally, I save my jwt in a sessionStorage:

getDate = () => {
        console.log(JSON.parse(sessionStorage.getItem('token')));
        const data = {token: sessionStorage.getItem('token')};
        const requestInfo = {
            method:'GET',
            body: JSON.stringify({data}),
            headers: new Headers({
                    'Content-Type': 'application/json',
                    'jwt': sessionStorage.getItem('token')
            }),
        };
        console.log('chegouaq');
        fetch('http://localhost:9000/users', requestInfo)
        .then(response => {
            console.log('chegouaq2');
            if(response.ok){
                return response.json();
            }
            throw new Error("Token Invalido..")
        })
        .then(data => {
            console.log(JSON.stringify(data));
            return;
        })
        .catch(e => {
            this.setState({message: e.message})
            console.error(e);
        });
    }

我通过头部发送了jwt,但是遇到了麻烦,而且我不知道如何使用我的API进行验证

I send my jwt through head, but I'm having trouble and I don't know how to validate it with my API

我的路由器/用户:

app.route('/users')
        .all(app.auth.authenticate())
        .get((req,res)=>{
            usersController
                .getAll()
                .then(data => {
                    res.json(data);
                })
                .catch(error=>{
                    console.log(error);
                    res.status(400);
                });
    })

.all(app.auth.authenticate())

.all(app.auth.authenticate())

我在这里称呼我的护照策略

Here I call my passport strategy

这是我的策略:

const strategy = new Strategy(options,(payload, done) => {

        Users
        .findOne({where: payload.id})
        .then(user => {

            if(user){
                return done(null,{
                    id: user.id,
                    login: user.login
                });
            }
            return done(null,false);
        })
        .catch(error => done(error,null));

    });

    passport.use(strategy);
    return {
        initialize: () => passport.initialize(),
        authenticate: () => passport.authenticate('jwt', jwtConfig.session)
    };
}

我不知道如何发送我的jwt进行验证

I don't know how I will send my jwt to validate

我的主要app.js:

my main app.js:

const express = require('express');
const bodyParser = require('body-parser');

const indexRouter = require('./routes/index');
const usersRouter = require('./routes/users');
const authRouter = require('./routes/auth');

const authorization = require('./auth');

const config = require('./config/config');
const datasource = require('./config/datasource');

const Email = require('./utils/email');

const app = express();
const port = 9000;

app.set('port',port);
app.config = config;
app.email = new Email(app.config);
app.datasource = datasource(app);

console.log(app.config);

app.use(bodyParser.json({
limit: '5mb'
}));
app.use(function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    next();
  });
const auth = authorization(app);
app.use(auth.initialize());
app.auth = auth;

indexRouter(app);
usersRouter(app);
authRouter(app);

module.exports = app;

推荐答案

尝试如下更新授权标头:

Try updating the Authorization header as follows:

  headers: new Headers({
                    'Content-Type': 'application/json',
                    'Authorization': 'Bearer ' + sessionStorage.getItem('token')
            }),

这篇关于sessionStorage中的Jwt验证在后端做出反应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆