Skip to content

Commit 3f904ef

Browse files
authored
Merge pull request #26 from daxxog/dv/secure_compare
Refactor secret-based security to compare secrets using `secrets.compare_digest`
2 parents 87fcf21 + f9c7972 commit 3f904ef

File tree

1 file changed

+16
-13
lines changed

1 file changed

+16
-13
lines changed

fastapi_simple_security/_security_secret.py

Lines changed: 16 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,8 @@
33
import os
44
import uuid
55
import warnings
6+
from secrets import compare_digest
7+
from typing import Optional
68

79
from fastapi import Security
810
from fastapi.security import APIKeyHeader
@@ -50,7 +52,7 @@ def get_secret_value(self):
5052
)
5153

5254

53-
async def secret_based_security(header_param: str = Security(secret_header)):
55+
async def secret_based_security(header_param: Optional[str] = Security(secret_header)):
5456
"""
5557
Args:
5658
header_param: parsed header field secret_header
@@ -62,20 +64,21 @@ async def secret_based_security(header_param: str = Security(secret_header)):
6264
HTTPException if the authentication failed
6365
"""
6466

65-
# We simply return True if the given secret-key has the right value
66-
if header_param == secret.value:
67-
return True
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
6871

69-
# Error text without header param
70-
if not header_param:
71-
error = "secret_key must be passed as a header field"
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+
)
7279

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

8184
raise HTTPException(status_code=HTTP_403_FORBIDDEN, detail=error)

0 commit comments

Comments
 (0)