Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for extracting authentication params from www-authenticate header #237

Merged
merged 2 commits into from
Mar 18, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion fastapi_azure_auth/auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -165,7 +165,12 @@ async def __call__(self, request: HTTPConnection, security_scopes: SecurityScope
claims: dict[str, Any] = get_unverified_claims(access_token)
except Exception as error:
log.warning('Malformed token received. %s. Error: %s', access_token, error, exc_info=True)
raise Unauthorized(detail='Invalid token format', request=request) from error
raise Unauthorized(
detail='Invalid token format',
client_id=self.app_client_id,
authorization_url=self.authorization_url,
request=request,
) from error

user_is_guest: bool = is_guest(claims=claims)
if not self.allow_guest_users and user_is_guest:
Expand Down
15 changes: 11 additions & 4 deletions fastapi_azure_auth/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,11 +25,16 @@ def __init__(self, detail: str) -> None:
class UnauthorizedHttp(HTTPException):
"""HTTP exception for authentication failures"""

def __init__(self, detail: str) -> None:
def __init__(self, detail: str, authorization_url: str | None = None, client_id: str | None = None) -> None:
header_value = 'Bearer'
if authorization_url:
header_value += f', authorization_uri="{authorization_url}"'
if client_id:
header_value += f', client_id="{client_id}"'
super().__init__(
status_code=status.HTTP_401_UNAUTHORIZED,
detail={"error": "invalid_token", "message": detail},
headers={"WWW-Authenticate": "Bearer"},
headers={"WWW-Authenticate": header_value},
)


Expand Down Expand Up @@ -103,10 +108,12 @@ def InvalidRequest(detail: str, request: HTTPConnection) -> InvalidRequestHttp |
return InvalidRequestWebSocket(detail)


def Unauthorized(detail: str, request: HTTPConnection) -> UnauthorizedHttp | UnauthorizedWebSocket:
def Unauthorized(
detail: str, request: HTTPConnection, authorization_url: str | None = None, client_id: str | None = None
) -> UnauthorizedHttp | UnauthorizedWebSocket:
"""Factory function for unauthorized exceptions"""
if request.scope["type"] == "http":
return UnauthorizedHttp(detail)
return UnauthorizedHttp(detail, authorization_url, client_id)
return UnauthorizedWebSocket(detail)


Expand Down
36 changes: 36 additions & 0 deletions tests/single_tenant/test_single_tenant.py
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,7 @@ async def test_no_keys_to_decode_with(single_tenant_app, mock_openid_and_empty_k
'detail': {'error': 'invalid_token', 'message': 'Unable to verify token, no signing keys found'}
}
assert response.status_code == 401
assert response.headers['www-authenticate'] == 'Bearer'


@pytest.mark.anyio
Expand Down Expand Up @@ -159,6 +160,7 @@ async def test_invalid_token_claims(single_tenant_app, mock_openid_and_keys):
response = await ac.get('api/v1/hello')
assert response.json() == {'detail': {'error': 'invalid_token', 'message': 'Token contains invalid claims'}}
assert response.status_code == 401
assert response.headers['www-authenticate'] == 'Bearer'


@pytest.mark.anyio
Expand All @@ -173,6 +175,7 @@ async def test_no_valid_keys_for_token(single_tenant_app, mock_openid_and_no_val
'detail': {'error': 'invalid_token', 'message': 'Unable to verify token, no signing keys found'}
}
assert response.status_code == 401
assert response.headers['www-authenticate'] == 'Bearer'


@pytest.mark.anyio
Expand Down Expand Up @@ -211,6 +214,7 @@ async def test_no_valid_invalid_formatted_scope(single_tenant_app, mock_openid_a
'detail': {'error': 'insufficient_scope', 'message': 'Token contains invalid formatted scopes'}
}
assert response.status_code == 403
assert response.headers['www-authenticate'] == 'Bearer'


@pytest.mark.anyio
Expand All @@ -223,6 +227,7 @@ async def test_expired_token(single_tenant_app, mock_openid_and_keys):
response = await ac.get('api/v1/hello')
assert response.json() == {'detail': {'error': 'invalid_token', 'message': 'Token signature has expired'}}
assert response.status_code == 401
assert response.headers['www-authenticate'] == 'Bearer'


@pytest.mark.anyio
Expand All @@ -236,6 +241,7 @@ async def test_evil_token(single_tenant_app, mock_openid_and_keys):
response = await ac.get('api/v1/hello')
assert response.json() == {'detail': {'error': 'invalid_token', 'message': 'Unable to validate token'}}
assert response.status_code == 401
assert response.headers['www-authenticate'] == 'Bearer'


@pytest.mark.anyio
Expand All @@ -247,6 +253,10 @@ async def test_malformed_token(single_tenant_app, mock_openid_and_keys):
response = await ac.get('api/v1/hello')
assert response.json() == {'detail': {'error': 'invalid_token', 'message': 'Invalid token format'}}
assert response.status_code == 401
assert (
response.headers['www-authenticate']
== 'Bearer, authorization_uri="https://login.microsoftonline.com/intility_tenant_id/oauth2/v2.0/authorize", client_id="oauth299-9999-9999-abcd-efghijkl1234567890"'
)


@pytest.mark.anyio
Expand All @@ -263,6 +273,10 @@ async def test_only_header(single_tenant_app, mock_openid_and_keys):
response = await ac.get('api/v1/hello')
assert response.json() == {'detail': {'error': 'invalid_token', 'message': 'Invalid token format'}}
assert response.status_code == 401
assert (
response.headers['www-authenticate']
== 'Bearer, authorization_uri="https://login.microsoftonline.com/intility_tenant_id/oauth2/v2.0/authorize", client_id="oauth299-9999-9999-abcd-efghijkl1234567890"'
)


@pytest.mark.anyio
Expand All @@ -276,6 +290,10 @@ async def test_none_token(single_tenant_app, mock_openid_and_keys, mocker):
response = await ac.get('api/v1/hello')
assert response.json() == {'detail': {'error': 'invalid_token', 'message': 'Invalid token format'}}
assert response.status_code == 401
assert (
response.headers['www-authenticate']
== 'Bearer, authorization_uri="https://login.microsoftonline.com/intility_tenant_id/oauth2/v2.0/authorize", client_id="oauth299-9999-9999-abcd-efghijkl1234567890"'
)


@pytest.mark.anyio
Expand All @@ -289,6 +307,8 @@ async def test_exception_raised(single_tenant_app, mock_openid_and_keys, mocker)
response = await ac.get('api/v1/hello')
assert response.json() == {'detail': {'error': 'invalid_token', 'message': 'Unable to process token'}}
assert response.status_code == 401
print(f"header: {response.headers.get('www-authenticate')}")
assert response.headers['www-authenticate'] == 'Bearer'


@pytest.mark.anyio
Expand Down Expand Up @@ -316,3 +336,19 @@ async def test_change_of_keys_works(single_tenant_app, mock_openid_ok_then_empty
'detail': {'error': 'invalid_token', 'message': 'Unable to verify token, no signing keys found'}
}
assert second_resonse.status_code == 401
assert 'www-authenticate' not in response.headers


@pytest.mark.anyio
async def test_authentication_params_from_header(single_tenant_app):
"""
* Send request with "Authorization: Bearer"
* Validate response provides authorization uri and client id in header
"""
async with AsyncClient(app=app, base_url='http://test', headers={'Authorization': 'Bearer'}) as ac:
response = await ac.get('api/v1/hello')
assert response.status_code == 401
assert (
response.headers['www-authenticate']
== 'Bearer, authorization_uri="https://login.microsoftonline.com/intility_tenant_id/oauth2/v2.0/authorize", client_id="oauth299-9999-9999-abcd-efghijkl1234567890"'
)
Loading