Skip to content

Commit 0a48b8b

Browse files
committed
feat: using secrets.compare_digest and making control flow clearer
1 parent 3f904ef commit 0a48b8b

File tree

1 file changed

+15
-16
lines changed

1 file changed

+15
-16
lines changed

fastapi_simple_security/_security_secret.py

Lines changed: 15 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -64,21 +64,20 @@ async def secret_based_security(header_param: Optional[str] = Security(secret_he
6464
HTTPException if the authentication failed
6565
"""
6666

67-
if header_param:
68-
# We simply return True if the given secret-key has the right value
69-
if compare_digest(header_param, secret.value):
70-
return True
67+
if not header_param:
68+
raise HTTPException(
69+
status_code=HTTP_403_FORBIDDEN,
70+
detail="secret_key must be passed as a header field",
71+
)
72+
73+
# We simply return True if the given secret-key has the right value
74+
if not compare_digest(header_param, secret.value):
75+
raise HTTPException(
76+
status_code=HTTP_403_FORBIDDEN,
77+
detail="Wrong secret key. If not set through environment variable \
78+
'FASTAPI_SIMPLE_SECURITY_SECRET', it was "
79+
"generated automatically at startup and appears in the server logs.",
80+
)
7181

72-
# Error text with wrong header param
73-
else:
74-
error = (
75-
"Wrong secret key. If not set through environment variable \
76-
'FASTAPI_SIMPLE_SECURITY_SECRET', it was "
77-
"generated automatically at startup and appears in the server logs."
78-
)
79-
80-
# Error text without header param
8182
else:
82-
error = "secret_key must be passed as a header field"
83-
84-
raise HTTPException(status_code=HTTP_403_FORBIDDEN, detail=error)
83+
return True

0 commit comments

Comments
 (0)