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

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

问题描述

另一个菜鸟问题.我正在使用 JWT 授权将我的用户登录到系统,获取令牌并将其保存在 localstorage 中,然后发送一个保存数据的 post 请求(它基本上是一个大表单).问题是,服务器在给定时间(20 分钟左右)后使令牌无效,因此,我的一些发布请求返回 401 状态.在发送 post 请求之前如何验证(如果需要,显示登录提示)?我正在使用 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天全站免登陆