3
3
import os
4
4
import uuid
5
5
import warnings
6
+ from secrets import compare_digest
7
+ from typing import Optional
6
8
7
9
from fastapi import Security
8
10
from fastapi .security import APIKeyHeader
@@ -50,7 +52,7 @@ def get_secret_value(self):
50
52
)
51
53
52
54
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 )):
54
56
"""
55
57
Args:
56
58
header_param: parsed header field secret_header
@@ -62,20 +64,21 @@ async def secret_based_security(header_param: str = Security(secret_header)):
62
64
HTTPException if the authentication failed
63
65
"""
64
66
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
68
71
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
+ )
72
79
73
- # Error text with wrong header param
80
+ # Error text without header param
74
81
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"
80
83
81
84
raise HTTPException (status_code = HTTP_403_FORBIDDEN , detail = error )
0 commit comments