在FastAPI中处理Google身份验证



我正在尝试在FastAPI应用程序上实现Google身份验证。

我有一个JWT的本地注册和登录系统,它运行得很好,但"get_current_user"方法取决于本地身份验证的oauth方案:

async def get_current_user(token: str = Depends(oauth2_scheme)):
credentials_exception = HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Could not validate credentials",
headers={"WWW-Authenticate": "Bearer"},
)
try:
payload = jwt.decode(token, settings.JWT_SECRET_KEY, algorithms=[ALGORITHM])
email: EmailStr = payload.get("sub")
if email is None:
raise credentials_exception
token_data = TokenData(email=email)
except JWTError:
raise credentials_exception
user = await User.find_one(User.email == EmailStr(token_data.email))
if user is None:
raise credentials_exception
return user

oauth2_scheme使用fastapi.security:

oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/jwt/login")

现在,问题是我不知道如何处理用户通过谷歌进行身份验证,因为我为谷歌定义了一个不同的Oauth客户端:

google_oauth = OAuth(starlette_config)
google_oauth.register(
name='google',
server_metadata_url='https://accounts.google.com/.well-known/openid-configuration',
client_kwargs={'scope': 'openid email profile'}
)

我的受保护路由依赖于"get_current_user"方法,该方法链接到本地oauth2_scheme。

我应该如何允许通过谷歌登录的用户访问我的受保护端点

from fastapi import Request, HTTPException
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials


class JWTBearer(HTTPBearer):
def __init__(self, auto_error: bool = True):
super(JWTBearer, self).__init__(auto_error=auto_error)
async def __call__(self, request: Request):
credentials: HTTPAuthorizationCredentials = await super(JWTBearer, self).__call__(request)
if credentials:
if not credentials.scheme == "Bearer":
raise HTTPException(status_code=403, detail="Invalid authentication scheme.")
#if not self.verify_jwt(credentials.credentials):
#    raise HTTPException(status_code=403, detail="Invalid token or expired token.")
return credentials.credentials
else:
raise HTTPException(status_code=403, detail="Invalid authorization code.")

现在将您的模式更改为

oauth2_schema = JWTBearer()

这将提供一种新的授权类型,只接受jwt令牌,而不是普通的密码和用户名。

型锻文件的工艺流程:

  1. 转到任何给您令牌的端点

  2. 复制令牌并单击挂锁图标

  3. 粘贴令牌,然后登录。

最新更新