-
Notifications
You must be signed in to change notification settings - Fork 143
feat: HMAC SHA256 Authentication #795
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
Merged
Merged
Changes from all commits
Commits
Show all changes
41 commits
Select commit
Hold shift + click to select a range
0c551dc
Initial work on HMAC implementation.
tswagger f634172
Authenticator test pass
tswagger 52b5d8b
Authenticator test pass
tswagger 1a7802e
Added HMAC Filter tests. Pass
tswagger 1cd518f
Added documentation
tswagger 91adb87
Added missing helper
tswagger 50d70e2
Minor syntax fix
tswagger 5be8b2c
Codeing standards cleanup
tswagger 89f38a8
Clarified Return statements
tswagger 2adcdbd
Update docs/guides/api_hmac_keys.md
tswagger bbc2496
Update docs/guides/api_hmac_keys.md
tswagger 1243efc
Minor typo fix, clarification of key vs secretKey
tswagger 498e685
Update docs/authentication.md
tswagger ac61035
Renamed 'HMAC' in the code to a consistent 'Hmac'
tswagger c8058f7
Update docs/authentication.md
tswagger 755a99c
Update docs/authentication.md
tswagger 19d7cea
Update docs/authentication.md
tswagger 72b9a70
Update docs/authentication.md
tswagger daee371
Update docs/guides/api_hmac_keys.md
tswagger 8990cef
Update docs/guides/api_hmac_keys.md
tswagger 5f56a55
Added ToC entries.
tswagger 4b452b9
Added CURLRequest example
tswagger 547e455
Update docs/guides/api_hmac_keys.md
tswagger 65853f7
Update docs/guides/api_hmac_keys.md
tswagger 9f9506d
Improved HMAC Docs
tswagger 7791f87
Updated phpdpd to suppress errors from HMAC Addition
tswagger b5d7fa1
Updated login recording to match JWT Authorization
tswagger d8e4262
Update src/Authentication/Authenticators/HmacSha256.php
tswagger 6ac224e
Added HMAC References to installation documentation
tswagger 08e0b8e
Cleaned up table formatting in markdown
tswagger bbcf8b5
Updated byte size for HMAC Secret Key
tswagger f47891a
Update tests/Authentication/Authenticators/HmacAuthenticatorTest.php
tswagger 10147cf
Update tests/Authentication/Authenticators/HmacAuthenticatorTest.php
tswagger 2eb3588
Initial fix to PHPStan errors
tswagger 37c9f82
Syntax adjustment
tswagger 58b6042
Added additional test
tswagger 76baf80
Added additional tests
tswagger f57f45f
Fix to test
tswagger 968997a
Removed redundant comment
tswagger a1b64db
Added config copy to Setup script
tswagger 9d223a4
Minor fix in docs
tswagger File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -20,6 +20,13 @@ | |
| - [Retrieving Access Tokens](#retrieving-access-tokens) | ||
| - [Access Token Lifetime](#access-token-lifetime) | ||
| - [Access Token Scopes](#access-token-scopes) | ||
| - [HMAC SHA256 Token Authenticator](#hmac-sha256-token-authenticator) | ||
| - [HMAC Keys/API Authentication](#hmac-keysapi-authentication) | ||
| - [Generating HMAC Access Keys](#generating-hmac-access-keys) | ||
| - [Revoking HMAC Keys](#revoking-hmac-keys) | ||
| - [Retrieving HMAC Keys](#retrieving-hmac-keys) | ||
| - [HMAC Keys Lifetime](#hmac-keys-lifetime) | ||
| - [HMAC Keys Scopes](#hmac-keys-scopes) | ||
|
|
||
| Authentication is the process of determining that a visitor actually belongs to your website, | ||
| and identifying them. Shield provides a flexible and secure authentication system for your | ||
|
|
@@ -38,6 +45,7 @@ public $authenticators = [ | |
| // alias => classname | ||
| 'session' => Session::class, | ||
| 'tokens' => AccessTokens::class, | ||
| 'hmac' => HmacSha256::class, | ||
| ]; | ||
| ``` | ||
|
|
||
|
|
@@ -264,7 +272,7 @@ $tokens = $user->accessTokens(); | |
| ### Access Token Lifetime | ||
|
|
||
| Tokens will expire after a specified amount of time has passed since they have been used. | ||
| By default, this is set to 1 year. You can change this value by setting the `accessTokenLifetime` | ||
| By default, this is set to 1 year. You can change this value by setting the `$unusedTokenLifetime` | ||
| value in the `Auth` config file. This is in seconds so that you can use the | ||
| [time constants](https://codeigniter.com/user_guide/general/common_functions.html#time-constants) | ||
| that CodeIgniter provides. | ||
|
|
@@ -303,3 +311,161 @@ if ($user->tokenCant('forums.manage')) { | |
| // do something.... | ||
| } | ||
| ``` | ||
|
|
||
| ## HMAC SHA256 Token Authenticator | ||
|
|
||
| The HMAC-SHA256 authenticator supports the use of revocable API keys without using OAuth. This provides | ||
| an alternative to a token that is passed in every request and instead uses a shared secret that is used to sign | ||
| the request in a secure manner. Like authorization tokens, these are commonly used to provide third-party developers | ||
| access to your API. These keys typically have a very long expiration time, often years. | ||
|
|
||
| These are also suitable for use with mobile applications. In this case, the user would register/sign-in | ||
| with their email/password. The application would create a new access token for them, with a recognizable | ||
| name, like John's iPhone 12, and return it to the mobile application, where it is stored and used | ||
| in all future requests. | ||
|
|
||
| > **Note** | ||
| > For the purpose of this documentation, and to maintain a level of consistency with the Authorization Tokens, | ||
| > the term "Token" will be used to represent a set of API Keys (key and secretKey). | ||
|
|
||
| ### Usage | ||
tswagger marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| In order to use HMAC Keys/Token the `Authorization` header will be set to the following in the request: | ||
|
|
||
| ``` | ||
| Authorization: HMAC-SHA256 <key>:<HMAC-HASH-of-request-body> | ||
| ``` | ||
|
|
||
| The code to do this will look something like this: | ||
|
|
||
| ```php | ||
| header("Authorization: HMAC-SHA256 {$key}:" . hash_hmac('sha256', $requestBody, $secretKey)); | ||
tswagger marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| ``` | ||
|
|
||
| Using the CodeIgniter CURLRequest class: | ||
tswagger marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| ```php | ||
| <?php | ||
|
|
||
| $client = \Config\Services::curlrequest(); | ||
|
|
||
| $key = 'a6c460151b4cabbe1c1d73e08915ce8e'; | ||
| $secretKey = '56c85232f0e5b55c05015476cd132c8d'; | ||
| $requestBody = '{"name":"John","email":"[email protected]"}'; | ||
|
|
||
| // $hashValue = b22b0ec11ad61cd4488ab1a09c8a0317e896c22adcc5754ea4cfd0f903a0f8c2 | ||
| $hashValue = hash_hmac('sha256', $requestBody, $secretKey); | ||
|
|
||
| $response = $client->setHeader('Authorization', "HMAC-SHA256 {$key}:{$hashValue}") | ||
| ->setBody($requestBody) | ||
| ->request('POST', 'https://example.com/api'); | ||
| ``` | ||
|
|
||
| ### HMAC Keys/API Authentication | ||
|
|
||
| Using HMAC keys requires that you either use/extend `CodeIgniter\Shield\Models\UserModel` or | ||
| use the `CodeIgniter\Shield\Authentication\Traits\HasHmacTokens` on your own user model. This trait | ||
| provides all the custom methods needed to implement HMAC keys in your application. The necessary | ||
| database table, `auth_identities`, is created in Shield's only migration class, which must be run | ||
| before first using any of the features of Shield. | ||
|
|
||
| ### Generating HMAC Access Keys | ||
|
|
||
| Access keys/tokens are created through the `generateHmacToken()` method on the user. This takes a name to | ||
| give to the token as the first argument. The name is used to display it to the user, so they can | ||
| differentiate between multiple tokens. | ||
|
|
||
| ```php | ||
| $token = $user->generateHmacToken('Work Laptop'); | ||
| ``` | ||
|
|
||
| This creates the keys/tokens using a cryptographically secure random string. The keys operate as shared keys. | ||
| This means they are stored as-is in the database. The method returns an instance of | ||
| `CodeIgniters\Shield\Authentication\Entities\AccessToken`. The field `secret` is the 'key' the field `secret2` is | ||
| the shared 'secretKey'. Both are required to when using this authentication method. | ||
|
|
||
| **The plain text version of these keys should be displayed to the user immediately, so they can copy it for | ||
| their use.** It is recommended that after that only the 'key' field is displayed to a user. If a user loses the | ||
| 'secretKey', they should be required to generate a new set of keys to use. | ||
|
|
||
| ```php | ||
| $token = $user->generateHmacToken('Work Laptop'); | ||
|
|
||
| echo 'Key: ' . $token->secret; | ||
| echo 'SecretKey: ' . $token->secret2; | ||
| ``` | ||
|
|
||
| ### Revoking HMAC Keys | ||
|
|
||
| HMAC keys can be revoked through the `revokeHmacToken()` method. This takes the key as the only | ||
| argument. Revoking simply deletes the record from the database. | ||
|
|
||
| ```php | ||
| $user->revokeHmacToken($key); | ||
| ``` | ||
|
|
||
| You can revoke all HMAC Keys with the `revokeAllHmacTokens()` method. | ||
|
|
||
| ```php | ||
| $user->revokeAllHmacTokens(); | ||
| ``` | ||
|
|
||
| ### Retrieving HMAC Keys | ||
|
|
||
| The following methods are available to help you retrieve a user's HMAC keys: | ||
|
|
||
| ```php | ||
| // Retrieve a set of HMAC Token/Keys by key | ||
| $token = $user->getHmacToken($key); | ||
|
|
||
| // Retrieve an HMAC token/keys by its database ID | ||
| $token = $user->getHmacTokenById($id); | ||
|
|
||
| // Retrieve all HMAC tokens as an array of AccessToken instances. | ||
| $tokens = $user->hmacTokens(); | ||
| ``` | ||
|
|
||
| ### HMAC Keys Lifetime | ||
|
|
||
| HMAC Keys/Tokens will expire after a specified amount of time has passed since they have been used. | ||
| This uses the same configuration value as AccessTokens. | ||
tswagger marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| By default, this is set to 1 year. You can change this value by setting the `$unusedTokenLifetime` | ||
| value in the `Auth` config file. This is in seconds so that you can use the | ||
| [time constants](https://codeigniter.com/user_guide/general/common_functions.html#time-constants) | ||
| that CodeIgniter provides. | ||
|
|
||
| ```php | ||
| public $unusedTokenLifetime = YEAR; | ||
| ``` | ||
|
|
||
| ### HMAC Keys Scopes | ||
|
|
||
| Each token (set of keys) can be given one or more scopes they can be used within. These can be thought of as | ||
| permissions the token grants to the user. Scopes are provided when the token is generated and | ||
| cannot be modified afterword. | ||
|
|
||
| ```php | ||
| $token = $user->gererateHmacToken('Work Laptop', ['posts.manage', 'forums.manage']); | ||
| ``` | ||
|
|
||
| By default, a user is granted a wildcard scope which provides access to all scopes. This is the | ||
| same as: | ||
|
|
||
| ```php | ||
| $token = $user->gererateHmacToken('Work Laptop', ['*']); | ||
| ``` | ||
|
|
||
| During authentication, the HMAC Keys the user used is stored on the user. Once authenticated, you | ||
| can use the `hmacTokenCan()` and `hmacTokenCant()` methods on the user to determine if they have access | ||
| to the specified scope. | ||
|
|
||
| ```php | ||
| if ($user->hmacTokenCan('posts.manage')) { | ||
| // do something.... | ||
| } | ||
|
|
||
| if ($user->hmacTokenCant('forums.manage')) { | ||
| // do something.... | ||
| } | ||
| ``` | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,115 @@ | ||
| # Protecting an API with HMAC Keys | ||
|
|
||
| > **Note** | ||
| > For the purpose of this documentation and to maintain a level of consistency with the Authorization Tokens, | ||
| the term "Token" will be used to represent a set of API Keys (key and secretKey). | ||
|
|
||
| HMAC Keys can be used to authenticate users for your own site, or when allowing third-party developers to access your | ||
| API. When making requests using HMAC keys, the token should be included in the `Authorization` header as an | ||
| `HMAC-SHA256` token. | ||
|
|
||
| > **Note** | ||
| > By default, `$authenticatorHeader['hmac']` is set to `Authorization`. You can change this value by | ||
| > setting the `$authenticatorHeader['hmac']` value in the **app/Config/Auth.php** config file. | ||
|
|
||
| Tokens are issued with the `generateHmacToken()` method on the user. This returns a | ||
| `CodeIgniter\Shield\Entities\AccessToken` instance. These shared keys are saved to the database in plain text. The | ||
| `AccessToken` object returned when you generate it will include a `secret` field which will be the `key` and a `secret2` | ||
| field that will be the `secretKey`. You should display the `secretKey` to your user once, so they have a chance to copy | ||
| it somewhere safe, as this is the only time you should reveal this key. | ||
|
|
||
| The `generateHmacToken()` method requires a name for the token. These are free strings and are often used to identify | ||
| the user/device the token was generated from/for, like 'Johns MacBook Air'. | ||
|
|
||
| ```php | ||
| $routes->get('/hmac/token', static function () { | ||
| $token = auth()->user()->generateHmacToken(service('request')->getVar('token_name')); | ||
|
|
||
| return json_encode(['key' => $token->secret, 'secretKey' => $token->secret2]); | ||
| }); | ||
| ``` | ||
|
|
||
| You can access all the user's HMAC keys with the `hmacTokens()` method on that user. | ||
|
|
||
| ```php | ||
| $tokens = $user->hmacTokens(); | ||
| foreach ($tokens as $token) { | ||
| // | ||
| } | ||
| ``` | ||
|
|
||
| ### Usage | ||
tswagger marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| In order to use HMAC Keys/Token the `Authorization` header will be set to the following in the request: | ||
|
|
||
| ``` | ||
| Authorization: HMAC-SHA256 <key>:<HMAC HASH of request body> | ||
| ``` | ||
|
|
||
| The code to do this will look something like this: | ||
|
|
||
| ```php | ||
| header("Authorization: HMAC-SHA256 {$key}:" . hash_hmac('sha256', $requestBody, $secretKey)); | ||
| ``` | ||
|
|
||
| ## HMAC Keys Permissions | ||
|
|
||
| HMAC keys can be given `scopes`, which are basically permission strings, for the HMAC Token/Keys. This is generally not | ||
| the same as the permission the user has, but is used to specify the permissions on the API itself. If not specified, the | ||
| token is granted all access to all scopes. This might be enough for a smaller API. | ||
|
|
||
| ```php | ||
| $token = $user->generateHmacToken('token-name', ['users-read']); | ||
| return json_encode(['key' => $token->secret, 'secretKey' => $token->secret2]); | ||
| ``` | ||
|
|
||
| > **Note** | ||
| > At this time, scope names should avoid using a colon (`:`) as this causes issues with the route filters being | ||
| > correctly recognized. | ||
|
|
||
| When handling incoming requests you can check if the token has been granted access to the scope with the `hmacTokenCan()` method. | ||
|
|
||
| ```php | ||
| if ($user->hmacTokenCan('users-read')) { | ||
| // | ||
| } | ||
| ``` | ||
|
|
||
| ### Revoking Keys/Tokens | ||
|
|
||
| Tokens can be revoked by deleting them from the database with the `revokeHmacToken($key)` or `revokeAllHmacTokens()` methods. | ||
|
|
||
| ```php | ||
| $user->revokeHmacToken($key); | ||
| $user->revokeAllHmacTokens(); | ||
| ``` | ||
|
|
||
| ## Protecting Routes | ||
|
|
||
| The first way to specify which routes are protected is to use the `hmac` controller filter. | ||
|
|
||
| For example, to ensure it protects all routes under the `/api` route group, you would use the `$filters` setting | ||
| on **app/Config/Filters.php**. | ||
|
|
||
| ```php | ||
| public $filters = [ | ||
| 'hmac' => ['before' => ['api/*']], | ||
| ]; | ||
| ``` | ||
|
|
||
| You can also specify the filter should run on one or more routes within the routes file itself: | ||
|
|
||
| ```php | ||
| $routes->group('api', ['filter' => 'hmac'], function($routes) { | ||
| // | ||
| }); | ||
| $routes->get('users', 'UserController::list', ['filter' => 'hmac:users-read']); | ||
| ``` | ||
|
|
||
| When the filter runs, it checks the `Authorization` header for a `HMAC-SHA256` value that has the computed token. It then | ||
| parses the raw token and looks it up the `key` portion in the database. Once found, it will rehash the body of the request | ||
| to validate the remainder of the Authorization raw token. If it passes the signature test it can determine the correct user, | ||
| which will then be available through an `auth()->user()` call. | ||
|
|
||
| > **Note** | ||
| > Currently only a single scope can be used on a route filter. If multiple scopes are passed in, only the first one is checked. | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.