auth with cookie

This commit is contained in:
Valentin CZERYBA 2023-10-20 22:26:48 +02:00
parent 878fbbf5df
commit 0d00df8194
3 changed files with 41 additions and 3 deletions

View File

@ -0,0 +1,38 @@
from fastapi.security import OAuth2
from fastapi.openapi.models import OAuthFlows as OAuthFlowsModel
from fastapi import Request
from fastapi.security.utils import get_authorization_scheme_param
from fastapi import HTTPException
from fastapi import status
from typing import Optional
from typing import Dict
class OAuth2PasswordBearerWithCookie(OAuth2):
def __init__(
self,
tokenUrl: str,
scheme_name: Optional[str] = None,
scopes: Optional[Dict[str, str]] = None,
auto_error: bool = True,
):
if not scopes:
scopes = {}
flows = OAuthFlowsModel(password={"tokenUrl": tokenUrl, "scopes": scopes})
super().__init__(flows=flows, scheme_name=scheme_name, auto_error=auto_error)
async def __call__(self, request: Request) -> Optional[str]:
authorization: str = request.cookies.get("access_token") #changed to accept access token from httpOnly Cookie
print("access_token is",authorization)
scheme, param = get_authorization_scheme_param(authorization)
if not authorization or scheme.lower() != "bearer":
if self.auto_error:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Not authenticated",
headers={"WWW-Authenticate": "Bearer"},
)
else:
return None
return param

View File

@ -8,14 +8,14 @@ from jose import JWTError, jwt
from passlib.context import CryptContext
from ..models import users, token
from ..dependencies import database
from ..dependencies import database, cookie
SECRET_KEY = "09d25e094faa6ca2556c818166b7a9563b93f7099f6f0f4caa6cf63b88e8d3e7"
ALGORITHM = "HS256"
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
oauth2_scheme = cookie.OAuth2PasswordBearerWithCookie(tokenUrl="token")
def verify_password(plain_password, hashed_password):
return pwd_context.verify(plain_password, hashed_password)

View File

@ -27,7 +27,7 @@ async def login_for_access_token(
)
content = {"message": "Access token generated"}
response = JSONResponse(content=content)
response.set_cookie(key="jwt", value=access_token)
response.set_cookie(key="access_token", value="Bearer {0}".format(access_token), httponly=True)
return response
@router.get("/token",tags=["token"])