FastAPI尽管在文档中已经认证,但显示”未认证”。

huangapple go评论66阅读模式
英文:

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).

huangapple
  • 本文由 发表于 2023年2月27日 02:17:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/75574088.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定