From ece32523850d9fa38ef353ee238461229f8ee840 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Mon, 10 Dec 2018 20:10:46 +0400 Subject: [PATCH] :sparkles: Add util class for OAuth2 Password Bearer scheme --- fastapi/security/__init__.py | 2 +- fastapi/security/oauth2.py | 19 +++++++++++++++++++ 2 files changed, 20 insertions(+), 1 deletion(-) diff --git a/fastapi/security/__init__.py b/fastapi/security/__init__.py index ba66dd54e..738cb8e52 100644 --- a/fastapi/security/__init__.py +++ b/fastapi/security/__init__.py @@ -1,4 +1,4 @@ from .api_key import APIKeyQuery, APIKeyHeader, APIKeyCookie from .http import HTTPBasic, HTTPBearer, HTTPDigest -from .oauth2 import OAuth2PasswordRequestForm, OAuth2 +from .oauth2 import OAuth2PasswordRequestForm, OAuth2, OAuth2PasswordBearer from .open_id_connect_url import OpenIdConnect diff --git a/fastapi/security/oauth2.py b/fastapi/security/oauth2.py index 717a3287f..608fa3555 100644 --- a/fastapi/security/oauth2.py +++ b/fastapi/security/oauth2.py @@ -3,7 +3,9 @@ from typing import List, Optional from fastapi.openapi.models import OAuth2 as OAuth2Model, OAuthFlows as OAuthFlowsModel from fastapi.security.base import SecurityBase from pydantic import BaseModel, Schema +from starlette.exceptions import HTTPException from starlette.requests import Request +from starlette.status import HTTP_403_FORBIDDEN class OAuth2PasswordRequestData(BaseModel): @@ -45,3 +47,20 @@ class OAuth2(SecurityBase): async def __call__(self, request: Request) -> str: 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