英文:
FastAPI "Not authenticated" despite being authenticated in docs
问题
以下是您的代码的中文翻译:
这是我的代码:
from fastapi import FastAPI, Depends
from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm
app = FastAPI()
Oauth_scheme = OAuth2PasswordBearer("token")
@app.post("/token")
async def token(token: OAuth2PasswordRequestForm = Depends()):
return {'access_token': 'someToken',}
@app.get('/', dependencies=[Depends(Oauth_scheme)])
async def root():
return {'data': 'someData',}
如果在Swagger中运行它,进行身份验证,然后我可以运行GET路由并获取数据。但如果我使用`http://127.0.0.1:8000/`在浏览器中访问它,我会得到以下输出:
detail "未经身份验证"
为什么会发生这种情况?我该如何修复它?
英文:
This is my code:
from fastapi import FastAPI, Depends
from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm
app = FastAPI()
Oauth_scheme = OAuth2PasswordBearer("token")
@app.post("/token")
async def token(token: OAuth2PasswordRequestForm = Depends()):
return {'access_token': 'someToken',}
@app.get('/', dependencies=[Depends(Oauth_scheme)])
async def root():
return {'data': 'someData',}
If run it in swagger, do authentication, then I am able to run get route and I get data out. But if I do hit my browser with http://127.0.0.1:8000/
I get out:
detail "Not authenticated"
Why is this happening? And how I fix it?
答案1
得分: 1
现在,您没有检查请求中是否包含的"token"是否正确。但是,由于您已经使用OAuth Token保护了您的API,您需要将一个token作为标头发送到"/"端点。
为了做到这一点,您可以使用任何客户端,如Postman、Python Requests、cURL等。
我在这里附上一个cURL的实现,但您可以轻松将其转换为Postman或任何其他客户端。
curl -X 'GET' \
'http://127.0.0.1:8000/' \
-H 'accept: application/json' \
-H 'Authorization: Bearer someToken'
这里,someToken可以是任何随机字符串(因为您没有检查token是否正确)。
英文:
Right now, you are not checking if the "token" that is coming with request is correct or not.
But, since you have protected your API with OAuth Token, you need to send a token as a header to /
endpoint.
In order to do that, you can use any Client like Postman, Python Requests, cURL etc.
I am attaching here an implementation of cURL, but you can easily convert this to postman or any other Client.
curl -X 'GET' \
'http://127.0.0.1:8000/' \
-H 'accept: application/json' \
-H 'Authorization: Bearer someToken'
Here, someToken can be any random string (because you are not checking whether the token is correct or not).
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论