Subhash Dasyam 1 month ago
committed by GitHub
parent
commit
dbacc14af2
No known key found for this signature in database GPG Key ID: B5690EEEBB952194
  1. 4
      fastapi/security/oauth2.py
  2. 6
      tests/test_security_oauth2_authorization_code_bearer.py
  3. 6
      tests/test_security_oauth2_password_bearer_optional.py

4
fastapi/security/oauth2.py

@ -536,7 +536,7 @@ class OAuth2PasswordBearer(OAuth2):
async def __call__(self, request: Request) -> str | None:
authorization = request.headers.get("Authorization")
scheme, param = get_authorization_scheme_param(authorization)
if not authorization or scheme.lower() != "bearer":
if not authorization or scheme.lower() != "bearer" or not param:
if self.auto_error:
raise self.make_not_authenticated_error()
else:
@ -642,7 +642,7 @@ class OAuth2AuthorizationCodeBearer(OAuth2):
async def __call__(self, request: Request) -> str | None:
authorization = request.headers.get("Authorization")
scheme, param = get_authorization_scheme_param(authorization)
if not authorization or scheme.lower() != "bearer":
if not authorization or scheme.lower() != "bearer" or not param:
if self.auto_error:
raise self.make_not_authenticated_error()
else:

6
tests/test_security_oauth2_authorization_code_bearer.py

@ -30,6 +30,12 @@ def test_incorrect_token():
assert response.json() == {"detail": "Not authenticated"}
def test_empty_bearer_token():
response = client.get("/items", headers={"Authorization": "Bearer "})
assert response.status_code == 401, response.text
assert response.json() == {"detail": "Not authenticated"}
def test_token():
response = client.get("/items", headers={"Authorization": "Bearer testtoken"})
assert response.status_code == 200, response.text

6
tests/test_security_oauth2_password_bearer_optional.py

@ -36,6 +36,12 @@ def test_incorrect_token():
assert response.json() == {"msg": "Create an account first"}
def test_empty_bearer_token():
response = client.get("/items", headers={"Authorization": "Bearer "})
assert response.status_code == 200, response.text
assert response.json() == {"msg": "Create an account first"}
def test_openapi_schema():
response = client.get("/openapi.json")
assert response.status_code == 200, response.text

Loading…
Cancel
Save