Skip to content

Commit ecfec86

Browse files
authored
Add usage instructions (#3)
1 parent 8ab2368 commit ecfec86

File tree

1 file changed

+47
-1
lines changed

1 file changed

+47
-1
lines changed

README.md

Lines changed: 47 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1,47 @@
1-
# guzzle-http-authentication-middleware
1+
# Guzzle HTTP Authentication Middleware
2+
3+
## Overview
4+
5+
[Middleware](http://docs.guzzlephp.org/en/stable/handlers-and-middleware.html#middleware) for [Guzzle 6](http://docs.guzzlephp.org/en/stable/) for setting [basic http authentication](https://en.wikipedia.org/wiki/Basic_access_authentication) on all requests sent by a client.
6+
7+
An authentication header is added to any valid request. A valid request is one where the request host matches a pre-specified domain name.
8+
9+
Useful if your circumstances match all or some of the following:
10+
11+
- you need to set HTTP authentication on all requests sent by a client for a specific domain only
12+
- you don't want to specifically add an authorization header to each request made, particularly if there are many points across an application where requests are made
13+
- you cannot determine in advance to which domains requests might be made and you don't want to leak credentials by means of setting an authorization header on every single request that your client sends
14+
15+
Maybe, just maybe, this is for you.
16+
17+
## Usage example
18+
19+
```php
20+
use GuzzleHttp\Client;
21+
use GuzzleHttp\HandlerStack;
22+
use webignition\Guzzle\Middleware\HttpAuthentication\HttpAuthenticationCredentials;
23+
use webignition\Guzzle\Middleware\HttpAuthentication\HttpAuthenticationMiddleware;
24+
25+
// Creating a client that uses the middleware
26+
$httpAuthenticationMiddleware = new HttpAuthenticationMiddleware();
27+
28+
$handlerStack = HandlerStack::create();
29+
$handlerStack->push($httpAuthenticationMiddleware, 'http-auth');
30+
31+
$client = new Client([
32+
'handler' => $handlerStack,
33+
]);
34+
35+
// Setting credentials on the middleware
36+
$credentials = new HttpAuthenticationCredentials('username', 'password', 'example.com');
37+
$httpAuthenticationMiddleware->setHttpAuthenticationCredentials($credentials);
38+
39+
// All requests to example.com (or *.example.com) will now have
40+
// a correct Authorization header set for basic HTTP authentication
41+
```
42+
## Application-level considerations
43+
44+
Let's assume you are building a modern PHP application that utilises controllers, services and so on.
45+
46+
Define your `HttpAuthenticationMiddleware` instance as a *service*. Use dependency injection to inject that service into whichever part of your application needs to set HTTP authentication credentials. Call `HttpAuthenticationMiddleware::setHttpAuthenticationCredentials()` as needed, passing in a `HttpAuthenticationCredentials` instance containing relevant values.
47+

0 commit comments

Comments
 (0)