React-如何在发送发布请求之前检查JWT是否有效? [英] React - How to check if JWT is valid before sending a post request?

查看:158
本文介绍了React-如何在发送发布请求之前检查JWT是否有效?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

另一个菜鸟问题.我正在使用JWT授权将用户登录到系统,获取令牌并将其保存在localstorage中,然后发送发布请求以保存数据(基本上是一种大格式).问题是,服务器在给定的时间(约20分钟)后使令牌失效,因此,我的一些发帖请求返回401 status.发送帖子请求之前如何验证(如果需要,显示登录提示)?我正在使用redux-form制作表单.

another noob question. I'm logging in my user to the system using JWT authorization, getting the token and saving it in localstorage and then sending a post request that saves data (its a big form basically). Problem is, the sever is invalidating the token after a given time (20 minutes or so) and so, some of my post requests are returning 401 status. How to verify (and if needed, show a login prompt) before sending the post request? I'm using redux-form to make my forms.

P.S:我知道我应该使用动作创建者之类的东西,但是我仍然是一个新手,所以在这些方面不太好.

P.S: I know I'm supposed to use action creators and such, but I'm still a newbie, so not very good at those stuff.

这是我的身份验证:

export function loginUser(creds) {

const data = querystring.stringify({_username: creds.username, _password: creds.password});

let config = {
    method: 'POST',
    headers: { 'Content-Type':'application/x-www-form-urlencoded' },
    body: data
};

return dispatch => {
    // We dispatch requestLogin to kickoff the call to the API
    dispatch(requestLogin(creds));

    return fetch(BASE_URL+'/login_check', config)
        .then(response =>
            response.json().then(user => ({ user, response }))
        ).then(({ user, response }) =>  {
            if (!response.ok) {
                // If there was a problem, we want to
                // dispatch the error condition
                dispatch(loginError(user.message));
                return Promise.reject(user)
            } else {
                // If login was successful, set the token in local storage
                localStorage.setItem('id_token', user.token);
                let token = localStorage.getItem('id_token')
                console.log(token);
                // Dispatch the success action
                dispatch(receiveLogin(user));
            }
        }).catch(err => console.log("Error: ", err))
    }
}

这是POST请求(我从redux-form获取values对象)

and here's the POST request (I'm getting the values object from redux-form)

const token = localStorage.getItem('id_token');
const AuthStr = 'Bearer '.concat(token);

let headers ={
headers: { 'Content-Type':'application/json','Authorization' : AuthStr }
};

export default (async function showResults(values, dispatch) {
axios.post(BASE_URL + '/new', values, headers)
    .then(function (response) {
        console.log(values);
        console.log(response);
    })
    .catch(function (error) {
        console.log(token);
        console.log(values)
        console.log(error.response);
    });
});

P.P.S:如果有人对我的代码有任何建议,请随时发表评论.

P.P.S: if anyone has any suggestion for improving my code, feel free to comment.

推荐答案

JWT到期可以通过两种方式进行检查.首先,您必须安装jsonwebtoken软件包,并在文件顶部要求它.此后,您可以按照以下方法在发送任何其余请求之前检查JWT到期.

JWT expiration can be checked in two ways. First of all you have to install jsonwebtoken package and require it at the top of your file. Thereafter, you can follow the below ways to check JWT expiration before sending any rest requests.

选项1

var isExpired = false;
const token = localStorage.getItem('id_token');
var decodedToken=jwt.decode(token, {complete: true});
var dateNow = new Date();

if(decodedToken.exp < dateNow.getTime())
    isExpired = true;

选项2

const token = localStorage.getItem('id_token');
jwt.verify(token, 'shhhhh', function(err, decoded) {
  if (err) {
    /*
      err = {
        name: 'TokenExpiredError',
        message: 'jwt expired',
        expiredAt: 1408621000
      }
    */
  }
});

检查该方法的错误.如果是TokenExpiredError,则表示令牌已过期.

Check the error of that method. If it is the TokenExpiredError then that means the token is expired.

这篇关于React-如何在发送发布请求之前检查JWT是否有效?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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