【问题标题】:Authorize button in swagger ui of FastAPIFastAPI的swagger ui中的授权按钮
【发布时间】:2022-02-24 03:20:23
【问题描述】:

我真的很困惑在 Fastapi 下面的 oauth 代码中需要 OAuth2PasswordRequestForm 和 OAuth2PasswordBearer。我有以下两个查询

  1. 谁负责在 swagger ui 中创建按钮?

from typing import Optional
from fastapi import Depends, FastAPI, HTTPException, status
from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm
from pydantic import BaseModel
import uvicorn

fake_users_db = {
    "johndoe": {
        "username": "johndoe",
        "full_name": "John Doe",
        "email": "johndoe@example.com",
        "hashed_password": "fakehashedsecret",
        "disabled": False,
    }
}

app = FastAPI()
def fake_hash_password(password: str):
    return "fakehashed" + password
    
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
    
class User(BaseModel):
    username: str
    email: Optional[str] = None
    full_name: Optional[str] = None
    disabled: Optional[bool] = None
    
class UserInDB(User):
    hashed_password: str

def get_user(db, username: str):
    if username in db:
        user_dict = db[username]
        return UserInDB(**user_dict)

def fake_decode_token(token):
    # This doesn't provide any security at all
    # Check the next version
    user = get_user(fake_users_db, token)
    return user

async def get_current_user(token: str = Depends(oauth2_scheme)):
    print("token value is....%s\n" % token)
    user = fake_decode_token(token)
    if not user:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Invalid authentication credentials",
            headers={"WWW-Authenticate": "Bearer"},
        )
    return user

async def get_current_active_user(current_user: User = Depends(get_current_user)):
    if current_user.disabled:
        raise HTTPException(status_code=400, detail="Inactive user")
    return current_user
    
@app.post("/token")
async def login(form_data: OAuth2PasswordRequestForm = Depends()):
    user_dict = fake_users_db.get(form_data.username)
    if not user_dict:
        raise HTTPException(status_code=400, detail="Incorrect username or password")
    user = UserInDB(**user_dict)
    hashed_password = fake_hash_password(form_data.password)
    if not hashed_password == user.hashed_password:
        raise HTTPException(status_code=400, detail="Incorrect username or password")

    return {"access_token": user.username, "token_type": "bearer"}
    
@app.get("/protected_hi")
async def protected_hi(current_user: User = Depends(get_current_active_user)):
    return "Hi! How are you? You are in a protected Zone."
   
if __name__ == "__main__":
    import uvicorn
    uvicorn.run('test:app', host="0.0.0.0", port=5000, reload=True)
  1. 当我通过单击“授权”按钮登录时,我可以访问名为“/protected_hi”的保护 API,但是如果我单击“/token”网址并填写用户/密码,而不是“授权”按钮。我无法访问受保护的 api。为什么这样? swagger UI 中的“Authorize”按钮和“/token”url 有什么用?我已经浏览了 fastapi 文档,但无法理解这部分。

【问题讨论】:

    标签: oauth-2.0 fastapi


    【解决方案1】:

    第一个问题:swagger 后端使用您编写的代码,并生成所谓的“文档”,它不是生产 GUI,因此该按钮仅用于帮助。

    区别在于:

    • 第一个:获取用户名和密码将它们发送到路由进行身份验证,获取结果并将其存储在导航器存储中,在您发送到 API 的每个请求中将其发送到标头中,(这和前端工程师做的一样)

    • 第二个:和其他任何东西一样是一个路由,它需要数据,然后返回数据,在你的情况下,它需要用户名和密码,并返回一个令牌,你制作这样的路由是因为 REST 是无状态的,而前端应该负责自定义该 API,并存储令牌,以便他们以后每次需要访问受保护的路由时发送它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-11-08
      • 2021-08-21
      • 1970-01-01
      • 2019-11-04
      • 2021-03-01
      • 2022-12-17
      • 2022-01-21
      • 2015-09-12
      相关资源
      最近更新 更多