[英]fastapi - optional OAuth2 authentication
I need to create a API with a route that is able to recognize if the current user is the one indicated in the request or not (also no auth should be valid)我需要创建一个 API ,其路由能够识别当前用户是否是请求中指示的用户(也没有身份验证应该是有效的)
For the others paths I followed https://fastapi.tiangolo.com/tutorial/security/oauth2-jwt/ and everything work with Bearer with JWT tokens like this对于其他路径,我遵循https://fastapi.tiangolo.com/tutorial/security/oauth2-jwt/并且一切都与带有 JWT 这样的令牌的 Bearer 一起使用
user: User = Depends(get_current_active_user)
Modifying the methods provided by the docs I tried with修改我尝试使用的文档提供的方法
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="auth")
async def get_user_or_none(db: Session = Depends(get_db), token: str = Depends(oauth2_scheme)):
"""
Return the current active user if is present (using the token Bearer) or None
"""
try:
payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
username: str = payload.get("sub")
if username is None:
return None
except JWTError:
return None
# check user in db
user = crud.get_user(db, username)
if user is None:
return None
return user
@router.get("/api/{user_id}/structure")
async def get_user_structure(
user_id: int,
user = Depends(get_user_or_none),
db: Session = Depends(get_db)
):
# do_something() if user.id == user_id else do_something_else()
but I receive an error但我收到一个错误
401 Error: Unauthorized {
"detail": "Not authenticated"
}
You need to use a different OAuth2PasswordBearer
for these optionally authenticated endpoints with auto_error=False
, eg您需要为这些可选的经过身份验证的端点使用不同的
OAuth2PasswordBearer
auto_error=False
,例如
optional_oauth2_scheme = OAuth2PasswordBearer(tokenUrl="auth", auto_error=False)
async def get_user_or_none(db: Session = Depends(get_db), token: str = Depends(optional_oauth2_scheme)):
...
Now the token will be None
when the Authorization
header isn't provided, resulting in your desired behavior.现在,当未提供
Authorization
header 时,令牌将为None
,从而产生您想要的行为。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.