问题描述
我正在使用 PostMan 解决我的 Angular/NodeJS 应用程序出现的奇怪的 400 错误.
I'm using PostMan to troubleshoot an odd 400 error with my Angular / NodeJS app.
我正在尝试获取 https://example.com/login.html
并且请求有两个标头:
I'm trying to GET https://example.com/login.html
and the request has two headers:
授权:承载 eyJ0eXAiOiJKV1QiLCJhbGc...==
和 Accept: text/html
这会返回 400 Bad Request
错误(服务器:cloudflare-nginx)
This returns a 400 Bad Request
error (server: cloudflare-nginx)
这很好用(返回 200
)如果:
我在本地环境中通过
http://localhost:5000/login.html
访问该文件(没有 https 因素?)-或-
I access the file in my local environment on
http://localhost:5000/login.html
(no https factor?) -or-
我从标题中删除 Authorization: Bearer
如果我查看我的 NodeJS 服务器日志,我什至看不到请求通过.所以 /login.html
甚至没有被击中,我认为是因为 Express 在我的 app.use(logger('dev'));
捡起它之前拒绝了它.
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.
更新:我相信 Cloudflare 会在请求到达 Heroku 之前将其退回 400.
UPDATE: I believe Cloudflare is kicking it back with 400 prior to the request ever reaching Heroku.
还有几点:
我正在使用 JWT 对用户进行身份验证,这就是 Bearer 令牌的来源.
I am using JWT to authenticate users, which is where the Bearer token comes from.
如果我使用 Bearer 令牌访问其他端点,例如 /profile
,它会通过解码令牌正确响应用户配置文件.
If I access other endpoints, such as /profile
with the Bearer token, it responds properly with the user profile from decoding the token.
我的问题是:
为什么这个请求在其他端点上工作时会是错误请求"?
Why would this request be a "Bad Request" when it works on other endpoints?
有没有办法在请求返回 400 之前捕捉到这一点并对其进行处理?
Is there a way to catch this and do something with the request before it's returned as 400?
推荐答案
事实证明,这个问题与我的 JWT 实现有关.出于某种原因,一个用户继续收到导致这 400 错误的令牌,即使该令牌已使用 JWT.io 验证为有效.
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:
我在令牌负载中嵌入了完整的用户配置文件(长 JSON).出于性能原因(小得多)和以防万一复杂负载中的某些东西导致问题,我将其缩减为仅他们的用户 ID.
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.
我在节点实现中从 JWT-Simple 切换到 jsonwebtoken
.
I switched from JWT-Simple to jsonwebtoken
in my node implementation.
我很高兴这有效.我的下一步是从授权"切换到x-encoded-auth"或其他一些自定义名称.
I'm just glad that worked. My next step was to switch from 'Authorization' to 'x-encoded-auth' or some other custom name.
这篇关于如果使用了授权承载令牌,则为 400 错误请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!