如果使用了授权承载令牌,则出现400错误的请求 [英] 400 Bad Request if Authorization Bearer token used
问题描述
我正在使用PostMan来解决我的Angular/NodeJS应用中的奇数400错误.
我正在尝试获取https://example.com/login.html
,并且该请求具有两个标头:
Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGc...==
和Accept: text/html
这将返回400 Bad Request
错误(服务器:cloudflare-nginx)
在以下情况下,此方法可以正常工作(返回200
):
-
我在
http://localhost:5000/login.html
上的本地环境中访问文件(没有https因素?)-或- -
我从标题中删除了
Authorization: Bearer
如果我查看NodeJS服务器日志,甚至看不到请求通过.所以/login.html
甚至都没有受到打击,我想是因为Express在我app.use(logger('dev'));
拿起它之前就拒绝了它.
更新:我相信Cloudflare会在请求到达Heroku之前将其退还400.
还有几点:
-
我正在使用JWT对用户进行身份验证,这就是Bearer令牌的来源.
-
如果我使用Bearer令牌访问其他端点,例如
/profile
,它将通过解码令牌对该用户配置文件做出正确响应.
我的问题是:
-
当此请求在其他端点上起作用时,为什么该请求为错误请求"?
-
在将请求返回为400之前,有没有办法捕获该请求并对其进行处理?
事实证明,该问题与我对JWT的实现有关.由于某种原因,即使使用JWT.io验证了令牌的有效性,一个用户仍然会收到导致这400个错误的令牌.
我进行了两项重大更改以解决此问题:
-
我正在将完整的用户配置文件(长JSON)嵌入令牌有效负载中.出于性能原因(尺寸小得多),以及万一复杂有效负载中的某些问题导致出现问题,我将其简化为他们的用户ID.
-
在我的节点实现中,我从JWT-Simple切换到了
jsonwebtoken
.
我很高兴能成功.我的下一步是从授权"切换到"x编码身份验证"或其他自定义名称.
I'm using PostMan to troubleshoot an odd 400 error with my Angular / NodeJS app.
I'm trying to GET https://example.com/login.html
and the request has two headers:
Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGc...==
and Accept: text/html
This returns a 400 Bad Request
error (server: cloudflare-nginx)
This works fine (returns 200
) if:
I access the file in my local environment on
http://localhost:5000/login.html
(no https factor?) -or-I remove
Authorization: Bearer
from the header
If I watch my NodeJS server logs, I don't even see the request come through. So /login.html
doesn't even get hit, I assume because Express is rejecting it before my app.use(logger('dev'));
picks it up.
UPDATE: I believe Cloudflare is kicking it back with 400 prior to the request ever reaching Heroku.
A few more points:
I am using JWT to authenticate users, which is where the Bearer token comes from.
If I access other endpoints, such as
/profile
with the Bearer token, it responds properly with the user profile from decoding the token.
My question is:
Why would this request be a "Bad Request" when it works on other endpoints?
Is there a way to catch this and do something with the request before it's returned as 400?
As it turns out, the issue was related to my implementation of JWT. For some reason, one user continued to receive a token that caused these 400 errors, even though the token was verified as valid using JWT.io.
I made two significant changes that fixed the issue:
I was embedding the full user profile (long JSON) in the token payload. I reduced it to just their userid, both for performance reasons (far smaller size) and just in case something in the complex payload was causing the issue.
I switched from JWT-Simple to
jsonwebtoken
in my node implementation.
I'm just glad that worked. My next step was to switch from 'Authorization' to 'x-encoded-auth' or some other custom name.
这篇关于如果使用了授权承载令牌,则出现400错误的请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!