让FastApi在标题中使用访问令牌
可能令人难以置信的愚蠢问题。
我有一个相当大的FastApi应用程序,现在我想将用户帐户添加到。我已经在
我的问题:访问生成令牌的路线时,我会得到一个访问令牌(如预期的)。但是,在下一次访问受保护的路线时,授权标题中未使用令牌,因此我会遇到一个未授权的错误。
我的问题:如何获得浏览器会话以将授权标头发送给令牌?
Incredibly dumb question probably.
I have a fairly large fastapi app that I now want to add user accounts to. I’ve settled on fastapi-login as it looks simple enough. I’ve implemented what in the readme page.
My problem: when visiting the route that generates a token, I get an access token (as expected). However, on a next visit to a protected route, the token isn’t used in the Authorization Header, hence I get a Not Authorized error.
My question: how can I get my browser sessions to send the authorization header with token?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您使用的是普通的HTML响应,则需要使用cookie登录。 软件包
fastapi-login
实现实际的cookie登录检查下面的代码以使用cookie使用
参考: https://github.com/mushroommaula/mushroommaula/fastroommaula/fastroommaula/fastapi_lastapi_loggin#usage-with -cookies
If you are using plain HTML response then you will need to use cookie to login. Check the below code to implement the actual cookie login with the package
fastapi-login
using cookies
Reference: https://github.com/MushroomMaula/fastapi_login#usage-with-cookies
您需要将令牌存储在客户端的某个地方,然后将其发送到每个请求的标题中。将其放在标题中的方式取决于您使用的库来执行HTTP请求。对于示例,如果您使用python
请求
库,这里是文档。但是,如果您的令牌被盗(例如,在CSRF攻击中),这仍然可以创建一些安全漏洞。我要做的是让代币的寿命很短(假设几秒钟),并且每当旧令牌即将到期时,就需要在背景线程上进行新的令牌。但是,当然,您需要同时访问令牌(例如,带有静音)。
You need to store the token somewhere on client side and then send it in the header of every request. How you put it in the header depends on the library you are using to perform HTTP requests. For exemple, if you use python
requests
library, here are the docs.However, this can still create some security vulnerabilities if your token is stolen (in a CSRF attack, for example). What I do is to let the token have a very short lifetime (let's say, some seconds) and demand a new token on a background thread whenever the old token is close to expire. But of course you need to take care with concurrent access to the token (with mutexes, for example).