mirror of https://github.com/tiangolo/fastapi.git
✨ Add util class for OAuth2 Password Bearer scheme
This commit is contained in:
parent
26ffa5d9c8
commit
ece3252385
|
|
@ -1,4 +1,4 @@
|
||||||
from .api_key import APIKeyQuery, APIKeyHeader, APIKeyCookie
|
from .api_key import APIKeyQuery, APIKeyHeader, APIKeyCookie
|
||||||
from .http import HTTPBasic, HTTPBearer, HTTPDigest
|
from .http import HTTPBasic, HTTPBearer, HTTPDigest
|
||||||
from .oauth2 import OAuth2PasswordRequestForm, OAuth2
|
from .oauth2 import OAuth2PasswordRequestForm, OAuth2, OAuth2PasswordBearer
|
||||||
from .open_id_connect_url import OpenIdConnect
|
from .open_id_connect_url import OpenIdConnect
|
||||||
|
|
|
||||||
|
|
@ -3,7 +3,9 @@ from typing import List, Optional
|
||||||
from fastapi.openapi.models import OAuth2 as OAuth2Model, OAuthFlows as OAuthFlowsModel
|
from fastapi.openapi.models import OAuth2 as OAuth2Model, OAuthFlows as OAuthFlowsModel
|
||||||
from fastapi.security.base import SecurityBase
|
from fastapi.security.base import SecurityBase
|
||||||
from pydantic import BaseModel, Schema
|
from pydantic import BaseModel, Schema
|
||||||
|
from starlette.exceptions import HTTPException
|
||||||
from starlette.requests import Request
|
from starlette.requests import Request
|
||||||
|
from starlette.status import HTTP_403_FORBIDDEN
|
||||||
|
|
||||||
|
|
||||||
class OAuth2PasswordRequestData(BaseModel):
|
class OAuth2PasswordRequestData(BaseModel):
|
||||||
|
|
@ -45,3 +47,20 @@ class OAuth2(SecurityBase):
|
||||||
|
|
||||||
async def __call__(self, request: Request) -> str:
|
async def __call__(self, request: Request) -> str:
|
||||||
return request.headers.get("Authorization")
|
return request.headers.get("Authorization")
|
||||||
|
|
||||||
|
|
||||||
|
class OAuth2PasswordBearer(OAuth2):
|
||||||
|
def __init__(self, tokenUrl: str, scheme_name: str = None, scopes: dict = None):
|
||||||
|
if not scopes:
|
||||||
|
scopes = {}
|
||||||
|
flows = OAuthFlowsModel(password={"tokenUrl": tokenUrl, "scopes": scopes})
|
||||||
|
super().__init__(flows=flows, scheme_name=scheme_name)
|
||||||
|
|
||||||
|
async def __call__(self, request: Request) -> str:
|
||||||
|
authorization: str = request.headers.get("Authorization")
|
||||||
|
if not authorization or "Bearer " not in authorization:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=HTTP_403_FORBIDDEN, detail="Not authenticated"
|
||||||
|
)
|
||||||
|
token = authorization.replace("Bearer ", "")
|
||||||
|
return token
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue