JsonWebTokenError:无效的令牌

时间:2019-11-18 18:59:26

标签: node.js reactjs jwt

您好,我正在尝试使用有效负载验证我的jwt,登录到前端时会生成jwt(我可以从前端获取它并保存到会话存储中) 而且我可以将jwt发回,并且我的验证仍然给出错误

我的路线(登录并签署我的jwt)

async login(req,res){
    const  user  = await User.existLogin(req.body.login);
    if (!user) { return res.status(400).json({result: 'Login is wrong '});} 
    const isPassword = await User.isPassword(user.dataValues.password, req.body.password);
    if (!isPassword) { return res.status(400).json({result: 'Password is wrong '}); } 
    const jwt = auth.signjwt(auth.payload(user));
    console.log(jwt);
    res.status(200);
    res.json(jwt);
}

我的前端-登录:

    signIn = () => {
        const requestInfo = {
            method:'POST',
            body: JSON.stringify({login:this.login,password:this.password}),
            headers: new Headers({
                'Content-Type': 'application/json'
            }),
        };
        fetch('http://localhost:8080/login', requestInfo)
        .then(response => {
            if(response.ok){
                return response.json();
            }
            throw new Error("Login Invalido..")
        })
        .then(token => {

            sessionStorage.setItem('token', JSON.stringify(token));
            this.props.history.push("/users");
            return;
        })
        .catch(e => {
            this.setState({message: e.message})
        });
    }

现在是我的有效负载函数和我的符号函数:

signjwt (payload) {
    return jwt.sign(payload, 
        config.secretToken
               )
},
payload (usuario) {
    return {
        sub: usuario.id,
        name: usuario.nome,
        email: usuario.email,
        login: usuario.username,
        admin: true,
        iat: Math.floor(moment.now()/1000), // Timestamp de hoje
        exp: moment().add(10, 'minutes').unix() // Validade de 2 dias
    }
},

我的前端 我的测试路线以验证我的jwt:

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

我的中间件尝试验证我的令牌

async auth(req,res,next){
    const token = req.header('Authorization');
    console.log(token);
    if(!token) return res.status(401).json('Unauthorized');
    try{
        const decoded = jwt.verify(token,config.secretToken);
        const user = await User.findByPk(decoded.sub);
        console.log(user);
        if(!user){
            return res.status(404).json('User not Found');
        }
        res.json(user);
        next();
    }catch(error){
        console.error(error);
        res.status(400).json('Invalid Token');
    }
}

ss: 我将console.log放在我的令牌上

"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOjIsImVtYWlsIjoiaGFiYm9vZ3JvQGdtYWlsLmNvbSIsImFkbWluIjp0cnVlLCJpYXQiOjE1NzQxMDI4MzcsImV4cCI6MTU3NDEwMzQzN30.UXsswlgXRd7E7-RIKkGU-6qknFy5CplwA0EXid9CfsQ"
JsonWebTokenError: invalid token
    at Object.module.exports [as verify] (C:\Users\SpiriT\Documents\ApiGame\node_modules\jsonwebtoken\verify.js:75:17)
    at auth (C:\Users\SpiriT\Documents\ApiGame\src\auth\index.js:28:33)
    at Layer.handle [as handle_request] (C:\Users\SpiriT\Documents\ApiGame\node_modules\express\lib\router\layer.js:95:5)
    at next (C:\Users\SpiriT\Documents\ApiGame\node_modules\express\lib\router\route.js:137:13)
    at Route.dispatch (C:\Users\SpiriT\Documents\ApiGame\node_modules\express\lib\router\route.js:112:3)
    at Layer.handle [as handle_request] (C:\Users\SpiriT\Documents\ApiGame\node_modules\express\lib\router\layer.js:95:5)
    at C:\Users\SpiriT\Documents\ApiGame\node_modules\express\lib\router\index.js:281:22
    at Function.process_params (C:\Users\SpiriT\Documents\ApiGame\node_modules\express\lib\router\index.js:335:12)
    at next (C:\Users\SpiriT\Documents\ApiGame\node_modules\express\lib\router\index.js:275:10)
    at Function.handle (C:\Users\SpiriT\Documents\ApiGame\node_modules\express\lib\router\index.js:174:3)
    at router (C:\Users\SpiriT\Documents\ApiGame\node_modules\express\lib\router\index.js:47:12)
    at Layer.handle [as handle_request] (C:\Users\SpiriT\Documents\ApiGame\node_modules\express\lib\router\layer.js:95:5)
    at trim_prefix (C:\Users\SpiriT\Documents\ApiGame\node_modules\express\lib\router\index.js:317:13)
    at C:\Users\SpiriT\Documents\ApiGame\node_modules\express\lib\router\index.js:284:7
    at Function.process_params (C:\Users\SpiriT\Documents\ApiGame\node_modules\express\lib\router\index.js:335:12)
    at next (C:\Users\SpiriT\Documents\ApiGame\node_modules\express\lib\router\index.js:275:10)
    at jsonParser (C:\Users\SpiriT\Documents\ApiGame\node_modules\body-parser\lib\types\json.js:110:7)
    at Layer.handle [as handle_request] (C:\Users\SpiriT\Documents\ApiGame\node_modules\express\lib\router\layer.js:95:5)
    at trim_prefix (C:\Users\SpiriT\Documents\ApiGame\node_modules\express\lib\router\index.js:317:13)
    at C:\Users\SpiriT\Documents\ApiGame\node_modules\express\lib\router\index.js:284:7
    at Function.process_params (C:\Users\SpiriT\Documents\ApiGame\node_modules\express\lib\router\index.js:335:12)
    at next (C:\Users\SpiriT\Documents\ApiGame\node_modules\express\lib\router\index.js:275:10) {
  name: 'JsonWebTokenError',
  message: 'invalid token'
}

1 个答案:

答案 0 :(得分:0)

我最终找到了原因: 我通过标题错误地处理了令牌: “授权”:sessionStorage.getItem(“令牌”)

是: '授权':JSON.parse(sessionStorage.getItem('token'))