-
-
Notifications
You must be signed in to change notification settings - Fork 13
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: add support for cookie authentication
- Loading branch information
1 parent
ea2bdb0
commit 9e8413d
Showing
2 changed files
with
83 additions
and
5 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,53 @@ | ||
from typing import Any, Optional, cast | ||
|
||
from fastapi.exceptions import HTTPException | ||
from fastapi.openapi.models import OAuthFlows as OAuthFlowsModel | ||
from fastapi.security import OAuth2 | ||
from fastapi.security.utils import get_authorization_scheme_param | ||
from starlette.requests import Request | ||
from starlette.status import HTTP_401_UNAUTHORIZED | ||
|
||
|
||
# This class is derived from FastAPI's OAuth2PasswordBearer class, | ||
# but adds support for cookie sessions. | ||
class OAuth2PasswordBearerOrAuthCookie(OAuth2): | ||
def __init__( | ||
self, | ||
tokenUrl: str, | ||
scheme_name: str | None = None, | ||
scopes: dict[str, str] | None = None, | ||
description: str | None = None, | ||
auto_error: bool = True, | ||
): | ||
if not scopes: | ||
scopes = {} | ||
flows = OAuthFlowsModel( | ||
password=cast(Any, {"tokenUrl": tokenUrl, "scopes": scopes}) | ||
) | ||
super().__init__( | ||
flows=flows, | ||
scheme_name=scheme_name, | ||
description=description, | ||
auto_error=auto_error, | ||
) | ||
|
||
async def __call__(self, request: Request) -> Optional[str]: | ||
authorization = request.headers.get("Authorization") | ||
session_cookie = request.cookies.get("session") | ||
scheme, param = get_authorization_scheme_param(authorization) | ||
|
||
# If a session cookie is present, use that instead of the | ||
# Authorization header. | ||
if session_cookie: | ||
return session_cookie | ||
|
||
if not authorization or scheme.lower() != "bearer": | ||
if self.auto_error: | ||
raise HTTPException( | ||
status_code=HTTP_401_UNAUTHORIZED, | ||
detail="Not authenticated", | ||
headers={"WWW-Authenticate": "Bearer"}, | ||
) | ||
else: | ||
return None | ||
return param |