【发布时间】:2020-07-10 12:46:02
【问题描述】:
目前我有以下用于私有路由的 React 组件
import { Route } from 'react-router-dom';
import React from 'react';
import { Redirect } from 'react-router';
import Cookies from 'js-cookie';
import jwtDecode from 'jwt-decode';
export default ({ component: Component, render: renderFn, authed, name, ...rest }) => {
var decoded = [];
decoded.permited = [];
var accesstoken = Cookies.get('accesstoken');
if((accesstoken)){
var decoded = jwtDecode(accesstoken)
}
return ( //Second case is for iframe based renders
<Route {...rest} render={props => ((authed === true) && (decoded.permited.includes(name) === true)) ? renderFn(props) : <Redirect to={{ pathname: '/login', state: { from: props.location } }} />} />
);
}
它工作正常,如果没有带有令牌的 cookie,它会重定向到登录。如果有,它会评估令牌中包含的您的权限,并据此让您输入特定路线或否。
当我插入一个带有随机值的 cookie 时,就会出现问题,例如 "undefined" 或 "thisisarandomstring"。当我这样做时,函数
if((accesstoken)){
var decoded = jwtDecode(accesstoken)
}
一直执行,jwtDecode崩溃,所以应用崩溃。
在尝试解码之前,我需要一种方法来检查传递的参数是否是访问令牌。或者类似的东西让它不会崩溃。
我试过这样的东西
export default ({ component: Component, render: renderFn, authed, name, ...rest }) => {
var decoded = [];
decoded.permited = [];
var accesstoken = Cookies.get('accesstoken');
console.log("first value")
console.log(accesstoken)
if(accesstoken === "undefined"){
console.log("value after equaled string")
accesstoken = undefined
console.log(accesstoken)
}
if((accesstoken)){
console.log("value in the decode")
var decoded = jwtDecode(accesstoken)
}
return ( //Second case is for iframe based renders
<Route {...rest} render={props => ((authed === true) && (decoded.permited.includes(name) === true)) ? renderFn(props) : <Redirect to={{ pathname: '/login', state: { from: props.location } }} />} />
);
}
如果检测到的字符串未定义,则尝试将值强制为真正的未定义,但无论如何它都会崩溃,因为由于某种原因它仍然会进入该解码 if。
我做了同样的检查,因为我的应用有时会设置一个值为“未定义”的字符串,因为我似乎无法在其他地方找到一些不受控制的错误,所以我想从私有路由中控制它。
但无论如何,理想的情况是在尝试解码之前检查它是否具有 jwt 格式或类似的格式。
知道我能做什么吗?
编辑:更多信息
它真的永远不会超过 jwtDecode() 函数,因为它返回一个错误
InvalidTokenError {message: "Invalid token specified: Cannot read property 'replace' of undefined"} message: "InvalidToken specified: Cannot read property 'replace' of undefined"
所以我不太确定如何处理,因为应用程序在那里崩溃,无法处理任何事情
【问题讨论】:
-
在此处使用 try catch 块...如果令牌未定义或不是有效的 JWT,则会抛出错误,您可以在 catch 块中处理它。
-
@hussain.codes 成功了。
标签: javascript reactjs jwt jwt-auth