JsonWebTokenError: jwt malformed: can't verify my Webtoken
Posted
技术标签:
【中文标题】JsonWebTokenError: jwt malformed: can\'t verify my Webtoken【英文标题】:JsonWebTokenError: jwt malformed: can't verify my WebtokenJsonWebTokenError: jwt malformed: can't verify my Webtoken 【发布时间】:2020-12-25 05:03:04 【问题描述】:我在我的实际项目中添加了令牌,但我在解码它们时遇到了问题:
我使用以下方法来解码令牌:
function verifyToken(req, res, next)
console.log(req.headers);
console.log(JSON.stringify(req.headers.authorization));
if(!req.headers.authorization)
return res.status(401).send('Unauthorized request!');
let token = req.headers.authorization.split(' ')[1];
console.log(token);
if(token === 'null')
return res.status(401).send('Unauthorized request!');
let payload = jwt.verify(token, 'secretKey');
if(!payload)
return res.status(401).send('Unauthorized request!');
req.userId = payload.subject;
next();
拦截方法:
intercept(req, next)
let storageService = this.injector.get(StorageService);
let token = '';
storageService.get(AuthConstants.AUTH).then(res =>
console.log("res: " + res + '\ntype: ' + typeof(res));
token = res;
);
let tokenizedReq = req.clone(
setHeaders:
Authorization: `Bearer $token`
);
return next.handle(tokenizedReq);
编辑:
存储服务:
async store(storageKey: string, value: any)
const encryptedValue = btoa(escape(JSON.stringify(value)));
await Storage.set(
key: storageKey,
value: encryptedValue
);
async get(storageKey: string)
const res = await Storage.get( key: storageKey )
if(res.value)
return JSON.parse(unescape(atob(res.value)));
else
return false;
现在有以下问题: res 有token的值,并将其分配给“token”。但是授权是通过 token='' 完成的。我认为这是因为 storageService.get() 函数是异步的。如何告诉我的代码在执行 req.clone 之前等待分配给令牌的数据?
【问题讨论】:
【参考方案1】:试试这个:
server.js
function verifyToken(req, res, next)
const token = req.header('Authorization');
if (!token) return res.status(401).send('Access Denied!');
try
const verified = jwt.verify(token, 'secretKey');
req.user = verified;
catch(err)
res.status(400).send('Invalid Token!');
auth.iterceptor.ts
let token = this.authService.getToken();
const updatedRequest = request.clone(
headers: request.headers.append("Authorization", "Bearer " + token)
);
【讨论】:
出现错误:throw er; // Unhandled 'error' event ^ Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
。我正在使用有效令牌测试该方法,但它返回“无效令牌”
我也添加了一个拦截器示例。检查这个
我发现了问题,我在上面的问题中添加了它。以上是关于JsonWebTokenError: jwt malformed: can't verify my Webtoken的主要内容,如果未能解决你的问题,请参考以下文章
JSONWebTokenError:JWT 在 index.js 处格式错误
JsonWebTokenError: jwt malformed: can't verify my Webtoken
为什么令牌上有JWT(JSON Web令牌)前缀?回复:JsonWebTokenError:无效令牌