新增KEYCLOAK_AUDIENCE,解决前后端认证失败的问题
This commit is contained in:
@@ -1,3 +1,4 @@
|
|||||||
|
# import logging
|
||||||
from uuid import UUID
|
from uuid import UUID
|
||||||
|
|
||||||
from fastapi import Depends, HTTPException, status
|
from fastapi import Depends, HTTPException, status
|
||||||
@@ -10,6 +11,8 @@ oauth2_optional = OAuth2PasswordBearer(
|
|||||||
tokenUrl=f"{settings.API_V1_STR}/auth/login", auto_error=False
|
tokenUrl=f"{settings.API_V1_STR}/auth/login", auto_error=False
|
||||||
)
|
)
|
||||||
|
|
||||||
|
# logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
async def get_current_keycloak_sub(
|
async def get_current_keycloak_sub(
|
||||||
token: str | None = Depends(oauth2_optional),
|
token: str | None = Depends(oauth2_optional),
|
||||||
@@ -28,8 +31,14 @@ async def get_current_keycloak_sub(
|
|||||||
algorithms = [settings.ALGORITHM]
|
algorithms = [settings.ALGORITHM]
|
||||||
|
|
||||||
try:
|
try:
|
||||||
payload = jwt.decode(token, key, algorithms=algorithms)
|
payload = jwt.decode(
|
||||||
|
token,
|
||||||
|
key,
|
||||||
|
algorithms=algorithms,
|
||||||
|
audience=settings.KEYCLOAK_AUDIENCE or None,
|
||||||
|
)
|
||||||
except JWTError as exc:
|
except JWTError as exc:
|
||||||
|
# logger.warning("Keycloak token validation failed: %s", exc)
|
||||||
raise HTTPException(
|
raise HTTPException(
|
||||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||||
detail="Invalid token",
|
detail="Invalid token",
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
from pydantic_settings import BaseSettings
|
from pathlib import Path
|
||||||
|
from pydantic_settings import BaseSettings, SettingsConfigDict
|
||||||
|
|
||||||
|
|
||||||
class Settings(BaseSettings):
|
class Settings(BaseSettings):
|
||||||
@@ -55,6 +56,7 @@ class Settings(BaseSettings):
|
|||||||
# Keycloak JWT (optional override)
|
# Keycloak JWT (optional override)
|
||||||
KEYCLOAK_PUBLIC_KEY: str = ""
|
KEYCLOAK_PUBLIC_KEY: str = ""
|
||||||
KEYCLOAK_ALGORITHM: str = "RS256"
|
KEYCLOAK_ALGORITHM: str = "RS256"
|
||||||
|
KEYCLOAK_AUDIENCE: str = ""
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def SQLALCHEMY_DATABASE_URI(self) -> str:
|
def SQLALCHEMY_DATABASE_URI(self) -> str:
|
||||||
@@ -67,9 +69,10 @@ class Settings(BaseSettings):
|
|||||||
f"@{self.METADATA_DB_HOST}:{self.METADATA_DB_PORT}/{self.METADATA_DB_NAME}"
|
f"@{self.METADATA_DB_HOST}:{self.METADATA_DB_PORT}/{self.METADATA_DB_NAME}"
|
||||||
)
|
)
|
||||||
|
|
||||||
class Config:
|
model_config = SettingsConfigDict(
|
||||||
env_file = ".env"
|
env_file=Path(__file__).resolve().parents[2] / ".env",
|
||||||
extra = "ignore"
|
extra="ignore",
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
settings = Settings()
|
settings = Settings()
|
||||||
|
|||||||
Reference in New Issue
Block a user