让FastApi在标题中使用访问令牌

发布于 2025-02-13 04:09:25 字数 184 浏览 1 评论 0原文

可能令人难以置信的愚蠢问题。

我有一个相当大的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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

囍孤女 2025-02-20 04:09:25

如果您使用的是普通的HTML响应,则需要使用cookie登录。 软件包fastapi-login实现实际的cookie登录

检查下面的代码以使用cookie使用

main.py

from fastapi import FastAPI, Response
from fastapi_login import LoginManager
from fastapi.security import OAuth2PasswordRequestForm
from fastapi_login.exceptions import InvalidCredentialsException

SECRET = 'your-secret-key'
manager = LoginManager(SECRET, token_url='/auth/token')

@manager.user_loader()
def load_user(email: str):  # could also be an asynchronous function
    # get actual username and password from db for the given email
    user = {"username": "[email protected]", "password": "secret"}
    return user

app = FastAPI()

# add cookie login route
@app.get('/auth')
def auth(response: Response, data: OAuth2PasswordRequestForm = Depends()):
    email = data.username
    password = data.password

    user = load_user(email)  # we are using the same function to retrieve the user
    if not user:
        raise InvalidCredentialsException  # you can also use your own HTTPException
    elif password != user['password']:
        raise InvalidCredentialsException
    # get token and set cookie
    token = manager.create_access_token(
        data=dict(sub=user.email)
    )
    manager.set_cookie(response, token)
    return response

# now add protected route
@app.get('/protected')
def protected_route(user=Depends(manager)):
    ...
    

参考: 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

main.py

from fastapi import FastAPI, Response
from fastapi_login import LoginManager
from fastapi.security import OAuth2PasswordRequestForm
from fastapi_login.exceptions import InvalidCredentialsException

SECRET = 'your-secret-key'
manager = LoginManager(SECRET, token_url='/auth/token')

@manager.user_loader()
def load_user(email: str):  # could also be an asynchronous function
    # get actual username and password from db for the given email
    user = {"username": "[email protected]", "password": "secret"}
    return user

app = FastAPI()

# add cookie login route
@app.get('/auth')
def auth(response: Response, data: OAuth2PasswordRequestForm = Depends()):
    email = data.username
    password = data.password

    user = load_user(email)  # we are using the same function to retrieve the user
    if not user:
        raise InvalidCredentialsException  # you can also use your own HTTPException
    elif password != user['password']:
        raise InvalidCredentialsException
    # get token and set cookie
    token = manager.create_access_token(
        data=dict(sub=user.email)
    )
    manager.set_cookie(response, token)
    return response

# now add protected route
@app.get('/protected')
def protected_route(user=Depends(manager)):
    ...
    

Reference: https://github.com/MushroomMaula/fastapi_login#usage-with-cookies

黄昏下泛黄的笔记 2025-02-20 04:09:25

您需要将令牌存储在客户端的某个地方,然后将其发送到每个请求的标题中。将其放在标题中的方式取决于您使用的库来执行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).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文