|
3 | 3 | # Licensed under the MIT License. See LICENSE.txt in the project root for
|
4 | 4 | # license information.
|
5 | 5 | # -------------------------------------------------------------------------
|
6 |
| -from typing import MutableMapping |
| 6 | +from typing import TypeVar, Any, MutableMapping |
7 | 7 |
|
| 8 | +from azure.core.pipeline import PipelineRequest |
8 | 9 | from azure.core.pipeline.policies import BearerTokenCredentialPolicy
|
9 |
| -from azure.cosmos import http_constants |
| 10 | +from azure.core.pipeline.transport import HttpRequest as LegacyHttpRequest |
| 11 | +from azure.core.rest import HttpRequest |
| 12 | + |
| 13 | +from .http_constants import HttpHeaders |
| 14 | + |
| 15 | +HTTPRequestType = TypeVar("HTTPRequestType", HttpRequest, LegacyHttpRequest) |
10 | 16 |
|
11 | 17 |
|
12 | 18 | class CosmosBearerTokenCredentialPolicy(BearerTokenCredentialPolicy):
|
13 | 19 |
|
14 | 20 | @staticmethod
|
15 | 21 | def _update_headers(headers: MutableMapping[str, str], token: str) -> None:
|
16 | 22 | """Updates the Authorization header with the bearer token.
|
17 |
| - This is the main method that differentiates this policy from core's BearerTokenCredentialPolicy and works |
18 |
| - to properly sign the authorization header for Cosmos' REST API. For more information: |
19 |
| - https://docs.microsoft.com/rest/api/cosmos-db/access-control-on-cosmosdb-resources#authorization-header |
20 | 23 |
|
21 |
| - :param dict headers: The HTTP Request headers |
| 24 | + :param MutableMapping[str, str] headers: The HTTP Request headers |
22 | 25 | :param str token: The OAuth token.
|
23 | 26 | """
|
24 |
| - headers[http_constants.HttpHeaders.Authorization] = f"type=aad&ver=1.0&sig={token}" |
| 27 | + headers[HttpHeaders.Authorization] = f"type=aad&ver=1.0&sig={token}" |
| 28 | + |
| 29 | + def on_request(self, request: PipelineRequest[HTTPRequestType]) -> None: |
| 30 | + """Called before the policy sends a request. |
| 31 | +
|
| 32 | + The base implementation authorizes the request with a bearer token. |
| 33 | +
|
| 34 | + :param ~azure.core.pipeline.PipelineRequest request: the request |
| 35 | + """ |
| 36 | + super().on_request(request) |
| 37 | + self._update_headers(request.http_request.headers, self._token.token) |
| 38 | + |
| 39 | + def authorize_request(self, request: PipelineRequest[HTTPRequestType], *scopes: str, **kwargs: Any) -> None: |
| 40 | + """Acquire a token from the credential and authorize the request with it. |
| 41 | +
|
| 42 | + Keyword arguments are passed to the credential's get_token method. The token will be cached and used to |
| 43 | + authorize future requests. |
| 44 | +
|
| 45 | + :param ~azure.core.pipeline.PipelineRequest request: the request |
| 46 | + :param str scopes: required scopes of authentication |
| 47 | + """ |
| 48 | + super().authorize_request(request, *scopes, **kwargs) |
| 49 | + self._update_headers(request.http_request.headers, self._token.token) |
0 commit comments