Auth (#65)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* Initial work towards auth * Add auth support * Add test for custom auth * Support auth-in-URL * Support auth-on-session
authored by Tom Christie · committed by GitHub · parent 2e9ab2e · Browse files · 4 files·+197 added−1 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
4 files+197 added−1 removed
- tests:+72 added−0 removed
- other:+125 added−1 removed
Provenance
- Commit
5afa7dd- Tree
a3f867c- Author
Tom Christie <tom@tomchristie.com>- Committer
GitHub <noreply@github.com>- Parent
2e9ab2e
4 files changed+197 added−1 removed
added:httpcore/auth.py+38 added
1+import typing2+from base64 import b64encode3+4+from .models import Request5+6+7+class AuthBase:8+ """9+ Base class that all auth implementations derive from.10+ """11+12+ def __call__(self, request: Request) -> Request:13+ raise NotImplementedError("Auth hooks must be callable.") # pragma: nocover14+15+16+class HTTPBasicAuth(AuthBase):17+ def __init__(18+ self, username: typing.Union[str, bytes], password: typing.Union[str, bytes]19+ ) -> None:20+ self.username = username21+ self.password = password22+23+ def __call__(self, request: Request) -> Request:24+ request.headers["Authorization"] = self.build_auth_header()25+ return request26+27+ def build_auth_header(self) -> str:28+ username, password = self.username, self.password29+30+ if isinstance(username, str):31+ username = username.encode("latin1")32+33+ if isinstance(password, str):34+ password = password.encode("latin1")35+36+ userpass = b":".join((username, password))37+ token = b64encode(userpass).decode().strip()38+ return f"Basic {token}"modified:httpcore/client.py+72 added-1 removed
1 import asyncio2 import typing3 from types import TracebackType4 5+from .auth import HTTPBasicAuth6 from .config import (7 DEFAULT_MAX_REDIRECTS,8 DEFAULT_POOL_LIMITS,9 DEFAULT_SSL_CONFIG,6 unmodified lines16 from .exceptions import RedirectBodyUnavailable, RedirectLoop, TooManyRedirects17 from .interfaces import ConcurrencyBackend, Dispatcher18 from .models import (19 URL,20+ AuthTypes,21 Headers,22 HeaderTypes,23 QueryParamTypes,24 Request,7 unmodified lines32 33 class AsyncClient:34 def __init__(35 self,36+ auth: AuthTypes = None,37 ssl: SSLConfig = DEFAULT_SSL_CONFIG,38 timeout: TimeoutConfig = DEFAULT_TIMEOUT_CONFIG,39 pool_limits: PoolLimits = DEFAULT_POOL_LIMITS,40 max_redirects: int = DEFAULT_MAX_REDIRECTS,4 unmodified lines45 dispatch = ConnectionPool(46 ssl=ssl, timeout=timeout, pool_limits=pool_limits, backend=backend47 )48 49+ self.auth = auth50 self.max_redirects = max_redirects51 self.dispatch = dispatch52 53 async def get(2 unmodified lines56 *,57 query_params: QueryParamTypes = None,58 headers: HeaderTypes = None,59 stream: bool = False,60+ auth: AuthTypes = None,61 allow_redirects: bool = True,62 ssl: SSLConfig = None,63 timeout: TimeoutConfig = None,64 ) -> Response:2 unmodified lines67 url,68 query_params=query_params,69 headers=headers,70 stream=stream,71+ auth=auth,72 allow_redirects=allow_redirects,73 ssl=ssl,74 timeout=timeout,75 )4 unmodified lines80 *,81 query_params: QueryParamTypes = None,82 headers: HeaderTypes = None,83 stream: bool = False,84+ auth: AuthTypes = None,85 allow_redirects: bool = True,86 ssl: SSLConfig = None,87 timeout: TimeoutConfig = None,88 ) -> Response:2 unmodified lines91 url,92 query_params=query_params,93 headers=headers,94 stream=stream,95+ auth=auth,96 allow_redirects=allow_redirects,97 ssl=ssl,98 timeout=timeout,99 )4 unmodified lines104 *,105 query_params: QueryParamTypes = None,106 headers: HeaderTypes = None,107 stream: bool = False,108+ auth: AuthTypes = None,109 allow_redirects: bool = False, # Note: Differs to usual default.110 ssl: SSLConfig = None,111 timeout: TimeoutConfig = None,112 ) -> Response:2 unmodified lines115 url,116 query_params=query_params,117 headers=headers,118 stream=stream,119+ auth=auth,120 allow_redirects=allow_redirects,121 ssl=ssl,122 timeout=timeout,123 )5 unmodified lines129 data: RequestData = b"",130 query_params: QueryParamTypes = None,131 headers: HeaderTypes = None,132 stream: bool = False,133+ auth: AuthTypes = None,134 allow_redirects: bool = True,135 ssl: SSLConfig = None,136 timeout: TimeoutConfig = None,137 ) -> Response:3 unmodified lines141 data=data,142 query_params=query_params,143 headers=headers,144 stream=stream,145+ auth=auth,146 allow_redirects=allow_redirects,147 ssl=ssl,148 timeout=timeout,149 )5 unmodified lines155 data: RequestData = b"",156 query_params: QueryParamTypes = None,157 headers: HeaderTypes = None,158 stream: bool = False,159+ auth: AuthTypes = None,160 allow_redirects: bool = True,161 ssl: SSLConfig = None,162 timeout: TimeoutConfig = None,163 ) -> Response:3 unmodified lines167 data=data,168 query_params=query_params,169 headers=headers,170 stream=stream,171+ auth=auth,172 allow_redirects=allow_redirects,173 ssl=ssl,174 timeout=timeout,175 )5 unmodified lines181 data: RequestData = b"",182 query_params: QueryParamTypes = None,183 headers: HeaderTypes = None,184 stream: bool = False,185+ auth: AuthTypes = None,186 allow_redirects: bool = True,187 ssl: SSLConfig = None,188 timeout: TimeoutConfig = None,189 ) -> Response:3 unmodified lines193 data=data,194 query_params=query_params,195 headers=headers,196 stream=stream,197+ auth=auth,198 allow_redirects=allow_redirects,199 ssl=ssl,200 timeout=timeout,201 )5 unmodified lines207 data: RequestData = b"",208 query_params: QueryParamTypes = None,209 headers: HeaderTypes = None,210 stream: bool = False,211+ auth: AuthTypes = None,212 allow_redirects: bool = True,213 ssl: SSLConfig = None,214 timeout: TimeoutConfig = None,215 ) -> Response:3 unmodified lines219 data=data,220 query_params=query_params,221 headers=headers,222 stream=stream,223+ auth=auth,224 allow_redirects=allow_redirects,225 ssl=ssl,226 timeout=timeout,227 )6 unmodified lines234 data: RequestData = b"",235 query_params: QueryParamTypes = None,236 headers: HeaderTypes = None,237 stream: bool = False,238+ auth: AuthTypes = None,239 allow_redirects: bool = True,240 ssl: SSLConfig = None,241 timeout: TimeoutConfig = None,242 ) -> Response:3 unmodified lines246 self.prepare_request(request)247 response = await self.send(248 request,249 stream=stream,250+ auth=auth,251 allow_redirects=allow_redirects,252 ssl=ssl,253 timeout=timeout,254 )6 unmodified lines261 self,262 request: Request,263 *,264 stream: bool = False,265+ auth: AuthTypes = None,266 ssl: SSLConfig = None,267 timeout: TimeoutConfig = None,268 allow_redirects: bool = True,269+ ) -> Response:270+ if auth is None:271+ auth = self.auth272+273+ url = request.url274+ if auth is None and (url.username or url.password):275+ auth = HTTPBasicAuth(username=url.username, password=url.password)276+277+ if auth is not None:278+ if isinstance(auth, tuple):279+ auth = HTTPBasicAuth(username=auth[0], password=auth[1])280+ request = auth(request)281+282+ response = await self.send_handling_redirects(283+ request,284+ stream=stream,285+ ssl=ssl,286+ timeout=timeout,287+ allow_redirects=allow_redirects,288+ )289+ return response290+291+ async def send_handling_redirects(292+ self,293+ request: Request,294+ *,295+ stream: bool = False,296+ ssl: SSLConfig = None,297+ timeout: TimeoutConfig = None,298+ allow_redirects: bool = True,299 history: typing.List[Response] = None,300 ) -> Response:301 if history is None:302 history = []20 unmodified lines323 324 async def send_next() -> Response:325 nonlocal request, response, ssl, allow_redirects, timeout, history326 request = self.build_redirect_request(request, response)276- response = await self.send(327+ response = await self.send_handling_redirects(328 request,329 stream=stream,330 allow_redirects=allow_redirects,331 ssl=ssl,93 unmodified lines425 426 class Client:427 def __init__(428 self,429+ auth: AuthTypes = None,430 ssl: SSLConfig = DEFAULT_SSL_CONFIG,431 timeout: TimeoutConfig = DEFAULT_TIMEOUT_CONFIG,432 pool_limits: PoolLimits = DEFAULT_POOL_LIMITS,433 max_redirects: int = DEFAULT_MAX_REDIRECTS,434 dispatch: Dispatcher = None,435 backend: ConcurrencyBackend = None,436 ) -> None:437 self._client = AsyncClient(438+ auth=auth,439 ssl=ssl,440 timeout=timeout,441 pool_limits=pool_limits,442 max_redirects=max_redirects,10 unmodified lines453 data: RequestData = b"",454 query_params: QueryParamTypes = None,455 headers: HeaderTypes = None,456 stream: bool = False,457+ auth: AuthTypes = None,458 allow_redirects: bool = True,459 ssl: SSLConfig = None,460 timeout: TimeoutConfig = None,461 ) -> SyncResponse:3 unmodified lines465 self.prepare_request(request)466 response = self.send(467 request,468 stream=stream,469+ auth=auth,470 allow_redirects=allow_redirects,471 ssl=ssl,472 timeout=timeout,473 )5 unmodified lines479 *,480 query_params: QueryParamTypes = None,481 headers: HeaderTypes = None,482 stream: bool = False,483+ auth: AuthTypes = None,484 allow_redirects: bool = True,485 ssl: SSLConfig = None,486 timeout: TimeoutConfig = None,487 ) -> SyncResponse:1 unmodified line489 "GET",490 url,491 headers=headers,492 stream=stream,493+ auth=auth,494 allow_redirects=allow_redirects,495 ssl=ssl,496 timeout=timeout,497 )4 unmodified lines502 *,503 query_params: QueryParamTypes = None,504 headers: HeaderTypes = None,505 stream: bool = False,506+ auth: AuthTypes = None,507 allow_redirects: bool = True,508 ssl: SSLConfig = None,509 timeout: TimeoutConfig = None,510 ) -> SyncResponse:1 unmodified line512 "OPTIONS",513 url,514 headers=headers,515 stream=stream,516+ auth=auth,517 allow_redirects=allow_redirects,518 ssl=ssl,519 timeout=timeout,520 )4 unmodified lines525 *,526 query_params: QueryParamTypes = None,527 headers: HeaderTypes = None,528 stream: bool = False,529+ auth: AuthTypes = None,530 allow_redirects: bool = False, # Note: Differs to usual default.531 ssl: SSLConfig = None,532 timeout: TimeoutConfig = None,533 ) -> SyncResponse:1 unmodified line535 "HEAD",536 url,537 headers=headers,538 stream=stream,539+ auth=auth,540 allow_redirects=allow_redirects,541 ssl=ssl,542 timeout=timeout,543 )5 unmodified lines549 data: RequestData = b"",550 query_params: QueryParamTypes = None,551 headers: HeaderTypes = None,552 stream: bool = False,553+ auth: AuthTypes = None,554 allow_redirects: bool = True,555 ssl: SSLConfig = None,556 timeout: TimeoutConfig = None,557 ) -> SyncResponse:2 unmodified lines560 url,561 data=data,562 headers=headers,563 stream=stream,564+ auth=auth,565 allow_redirects=allow_redirects,566 ssl=ssl,567 timeout=timeout,568 )5 unmodified lines574 data: RequestData = b"",575 query_params: QueryParamTypes = None,576 headers: HeaderTypes = None,577 stream: bool = False,578+ auth: AuthTypes = None,579 allow_redirects: bool = True,580 ssl: SSLConfig = None,581 timeout: TimeoutConfig = None,582 ) -> SyncResponse:2 unmodified lines585 url,586 data=data,587 headers=headers,588 stream=stream,589+ auth=auth,590 allow_redirects=allow_redirects,591 ssl=ssl,592 timeout=timeout,593 )5 unmodified lines599 data: RequestData = b"",600 query_params: QueryParamTypes = None,601 headers: HeaderTypes = None,602 stream: bool = False,603+ auth: AuthTypes = None,604 allow_redirects: bool = True,605 ssl: SSLConfig = None,606 timeout: TimeoutConfig = None,607 ) -> SyncResponse:2 unmodified lines610 url,611 data=data,612 headers=headers,613 stream=stream,614+ auth=auth,615 allow_redirects=allow_redirects,616 ssl=ssl,617 timeout=timeout,618 )5 unmodified lines624 data: RequestData = b"",625 query_params: QueryParamTypes = None,626 headers: HeaderTypes = None,627 stream: bool = False,628+ auth: AuthTypes = None,629 allow_redirects: bool = True,630 ssl: SSLConfig = None,631 timeout: TimeoutConfig = None,632 ) -> SyncResponse:2 unmodified lines635 url,636 data=data,637 headers=headers,638 stream=stream,639+ auth=auth,640 allow_redirects=allow_redirects,641 ssl=ssl,642 timeout=timeout,643 )5 unmodified lines649 self,650 request: Request,651 *,652 stream: bool = False,653+ auth: AuthTypes = None,654 allow_redirects: bool = True,655 ssl: SSLConfig = None,656 timeout: TimeoutConfig = None,657 ) -> SyncResponse:658 response = self._loop.run_until_complete(659 self._client.send(660 request,661 stream=stream,662+ auth=auth,663 allow_redirects=allow_redirects,664 ssl=ssl,665 timeout=timeout,666 )16 unmodified linesmodified:httpcore/models.py+15 added
41 unmodified lines42 typing.Dict[typing.AnyStr, typing.AnyStr],43 typing.List[typing.Tuple[typing.AnyStr, typing.AnyStr]],44 ]45 46+AuthTypes = typing.Union[47+ typing.Tuple[typing.Union[str, bytes], typing.Union[str, bytes]],48+ typing.Callable[["Request"], "Request"]49+]50+51 RequestData = typing.Union[dict, bytes, typing.AsyncIterator[bytes]]52 53 ResponseContent = typing.Union[bytes, typing.AsyncIterator[bytes]]54 43 unmodified lines98 def authority(self) -> str:99 return self.components.authority or ""100 101 @property102+ def username(self) -> str:103+ userinfo = self.components.userinfo or ""104+ return userinfo.partition(':')[0]105+106+ @property107+ def password(self) -> str:108+ userinfo = self.components.userinfo or ""109+ return userinfo.partition(':')[2]110+111+ @property112 def host(self) -> str:113 return self.components.host or ""114 115 @property724 unmodified linesadded:tests/client/test_auth.py+72 added
1+import json2+from urllib.parse import parse_qs3+4+import pytest5+6+from httpcore import (7+ URL,8+ Client,9+ Dispatcher,10+ Request,11+ Response,12+ SSLConfig,13+ TimeoutConfig,14+)15+16+17+class MockDispatch(Dispatcher):18+ async def send(19+ self,20+ request: Request,21+ stream: bool = False,22+ ssl: SSLConfig = None,23+ timeout: TimeoutConfig = None,24+ ) -> Response:25+ body = json.dumps({"auth": request.headers.get('Authorization')}).encode()26+ return Response(200, content=body, request=request)27+28+29+def test_basic_auth():30+ url = "https://example.org/"31+ auth = ('tomchristie', 'password123')32+33+ with Client(dispatch=MockDispatch()) as client:34+ response = client.get(url, auth=auth)35+36+ assert response.status_code == 20037+ assert json.loads(response.text) == {'auth': 'Basic dG9tY2hyaXN0aWU6cGFzc3dvcmQxMjM='}38+39+40+def test_basic_auth_in_url():41+ url = "https://tomchristie:password123@example.org/"42+43+ with Client(dispatch=MockDispatch()) as client:44+ response = client.get(url)45+46+ assert response.status_code == 20047+ assert json.loads(response.text) == {'auth': 'Basic dG9tY2hyaXN0aWU6cGFzc3dvcmQxMjM='}48+49+50+def test_basic_auth_on_session():51+ url = "https://example.org/"52+ auth = ('tomchristie', 'password123')53+54+ with Client(dispatch=MockDispatch(), auth=auth) as client:55+ response = client.get(url)56+57+ assert response.status_code == 20058+ assert json.loads(response.text) == {'auth': 'Basic dG9tY2hyaXN0aWU6cGFzc3dvcmQxMjM='}59+60+61+def test_custom_auth():62+ url = "https://example.org/"63+64+ def auth(request):65+ request.headers['Authorization'] = 'Token 123'66+ return request67+68+ with Client(dispatch=MockDispatch()) as client:69+ response = client.get(url, auth=auth)70+71+ assert response.status_code == 20072+ assert json.loads(response.text) == {'auth': 'Token 123'}