Skip to content
Merged
Show file tree
Hide file tree
Changes from 7 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
57 changes: 56 additions & 1 deletion docs/references/authentication/hmac.md
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,57 @@ You can revoke all HMAC Keys with the `revokeAllHmacTokens()` method.
$user->revokeAllHmacTokens();
```

## Expiring HMAC Keys

By default, the HMAC keys don't expire unless they meet the HMAC Keys lifetime expiration after their last used date.

HMAC keys can be set to expire through the `generateHmacToken()` method. This takes the expiration date as the $expiresAt argument. It's also possible to update an existing HMAC key using `setHmacTokenExpirationById($HmacTokenID, $expiresAt)`

`$expiresAt` [Time](/libraries/time.html) object

```php
// Expiration date = 2024-11-03 12:00:00
$expiresAt = Time::parse('2024-11-03 12:00:00');
$token = $this->user->generateHmacToken('foo', ['foo:bar'], $expiresAt);

// Expiration date = 2024-11-15 00:00:00
$expiresAt = Time::parse('2024-11-15 00:00:00');
$token = $user->setHmacTokenExpirationById($token->id, $expiresAt);

// Or Expiration date = 1 month + 15 days into the future
$expiresAt = Time::now()->addMonths(1)->addDays(15);
$token = $user->setHmacTokenExpirationById($token->id, $expiresAt);
```

The following support methods are also available:

`hasHmacTokenExpired(AccessToken $HmacToken)` - Checks if the HMAC key has expired. Returns `true` if the HMAC key has expired, `false` if not.

```php
$expiresAt = Time::parse('2024-11-03 12:00:00');
$token = $this->user->generateHmacToken('foo', ['foo.bar'], $expiresAt);

$this->user->hasHmacTokenExpired($token); // Returns true
```

`canHmacTokenExpire(AccessToken $HmacToken)` - Checks if HMAC key has an expiration set. Returns `true` or `false` accordingly.

```php
$expiresAt = Time::parse('2024-11-03 12:00:00');

$token = $this->user->generateHmacToken('foo', ['foo.bar'], $expiresAt);
$this->user->canHmacTokenExpire($token); // Returns true

$token2 = $this->user->generateHmacToken('bar');
$this->user->canHmacTokenExpire($token2); // Returns false
```

You can also easily set all existing HMAC keys/tokens as expired with the `spark` command:
```
php spark shield:hmac invalidateAll
```
**Careful!** This command invalidates _all_ keys for _all_ users.

## Retrieving HMAC Keys

The following methods are available to help you retrieve a user's HMAC keys:
Expand Down Expand Up @@ -217,7 +268,7 @@ Configure **app/Config/AuthToken.php** for your needs.

### HMAC Keys Lifetime

HMAC Keys/Tokens will expire after a specified amount of time has passed since they have been used.
HMAC Keys 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 `$unusedTokenLifetime`
value. This is in seconds so that you can use the
Expand All @@ -228,6 +279,10 @@ that CodeIgniter provides.
public $unusedTokenLifetime = YEAR;
```

### HMAC Keys Expiration vs Lifetime

Expiration and Lifetime are different concepts. The lifetime is the maximum time allowed for the HMAC Key to exist since its last use. HMAC Key expiration, on the other hand, is a set date in which the HMAC Key will cease to function.

### Login Attempt Logging

By default, only failed login attempts are recorded in the `auth_token_logins` table.
Expand Down
54 changes: 53 additions & 1 deletion docs/references/authentication/tokens.md
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,7 @@ Configure **app/Config/AuthToken.php** for your needs.

### Access Token Lifetime

Tokens will expire after a specified amount of time has passed since they have been used.
Tokens will expire after a specified amount of time has passed since they last have been used.

By default, this is set to 1 year.
You can change this value by setting the `$unusedTokenLifetime` value. This is
Expand All @@ -137,6 +137,58 @@ that CodeIgniter provides.
public $unusedTokenLifetime = YEAR;
```


## Expiring Access Tokens

By default, the Access Tokens don't expire unless they meet the Access Token lifetime expiration after their last used date.

Access Tokens can be set to expire through the `generateAccessToken()` method. This takes the expiration date as the $expiresAt argument. It's also possible to update an existing HMAC key using `setAccessTokenById($HmacTokenID, $expiresAt)`

`$expiresAt` [Time](/libraries/time.html) object

```php
// Expiration date = 2024-11-03 12:00:00
$expiresAt = Time::parse('2024-11-03 12:00:00');
$token = $this->user->generateAccessToken('foo', ['foo.bar'], $expiresAt);

// Expiration date = 2024-11-15 00:00:00
$expiresAt = Time::parse('2024-11-15 00:00:00');
$user->setAccessTokenExpirationById($token->id, $expiresAt);

// Or Expiration date = 1 month + 15 days into the future
$expiresAt = Time::now()->addMonths(1)->addDays(15);

$user->setAccessTokenExpirationById($token->id, $expiresAt);
```

The following support methods are also available:

`hasAccessTokenExpired(AccessToken $accessToken)` - Checks if Access Token has expired. Returns `true` if the Access Token has expired, `false` if not.

```php
$expiresAt = Time::parse('2024-11-03 12:00:00');

$token = $this->user->generateAccessToken('foo', ['foo.bar'], $expiresAt);

$this->user->hasAccessTokenExpired($token); // Returns true
```

`canAccessTokenExpire(AccessToken $HmacToken)` - Checks if Access Token has an expiration set. Returns `true` or `false` accordingly.

```php
$expiresAt = Time::parse('2024-11-03 12:00:00');

$token = $this->user->generateAccessToken('foo', ['foo.bar'], $expiresAt);
$this->user->canAccessTokenExpire($token2); // Returns false

$token2 = $this->user->generateAccessToken('bar');
$this->user->canAccessTokenExpire($token); // Returns true
```


### Access Token Expiration vs Lifetime
Expiration and Lifetime are different concepts. The lifetime is the maximum time allowed for the token to exist since its last use. Token expiration, on the other hand, is a set date in which the Access Token will cease to function.

### Login Attempt Logging

By default, only failed login attempts are recorded in the `auth_token_logins` table.
Expand Down
10 changes: 8 additions & 2 deletions phpstan-baseline.php
Original file line number Diff line number Diff line change
Expand Up @@ -168,7 +168,13 @@
$ignoreErrors[] = [
'message' => '#^Cannot access property \\$id on array\\<string, string\\>\\|object\\.$#',
'identifier' => 'property.nonObject',
'count' => 7,
'count' => 9,
'path' => __DIR__ . '/src/Commands/Hmac.php',
];
$ignoreErrors[] = [
'message' => '#^Cannot access property \\$expires on array\\<string, string\\>\\|object\\.$#',
'identifier' => 'property.nonObject',
'count' => 3,
'path' => __DIR__ . '/src/Commands/Hmac.php',
];
$ignoreErrors[] = [
Expand Down Expand Up @@ -259,7 +265,7 @@
$ignoreErrors[] = [
'message' => '#^Call to function model with CodeIgniter\\\\Shield\\\\Models\\\\UserIdentityModel\\:\\:class is discouraged\\.$#',
'identifier' => 'codeigniter.factoriesClassConstFetch',
'count' => 19,
'count' => 21,
'path' => __DIR__ . '/src/Entities/User.php',
];
$ignoreErrors[] = [
Expand Down
13 changes: 13 additions & 0 deletions src/Authentication/Authenticators/AccessTokens.php
Original file line number Diff line number Diff line change
Expand Up @@ -154,6 +154,19 @@ public function check(array $credentials): Result

assert($token->last_used_at instanceof Time || $token->last_used_at === null);

// Is expired ?
if (
$token->expires !== null
&& $token->expires->isBefore(
Time::now(),
)
) {
return new Result([
'success' => false,
'reason' => lang('Auth.oldToken'),
]);
}

// Hasn't been used in a long time
if (
$token->last_used_at
Expand Down
56 changes: 52 additions & 4 deletions src/Authentication/Traits/HasAccessTokens.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,11 @@

namespace CodeIgniter\Shield\Authentication\Traits;

use CodeIgniter\I18n\Time;
use CodeIgniter\Shield\Authentication\Authenticators\AccessTokens;
use CodeIgniter\Shield\Entities\AccessToken;
use CodeIgniter\Shield\Models\UserIdentityModel;
use InvalidArgumentException;

/**
* Trait HasAccessTokens
Expand All @@ -34,15 +37,18 @@ trait HasAccessTokens
/**
* Generates a new personal access token for this user.
*
* @param string $name Token name
* @param list<string> $scopes Permissions the token grants
* @param string $name Token name
* @param list<string> $scopes Permissions the token grants
* @param Time $expiresAt Expiration date
*
* @throws InvalidArgumentException
*/
public function generateAccessToken(string $name, array $scopes = ['*']): AccessToken
public function generateAccessToken(string $name, array $scopes = ['*'], ?Time $expiresAt = null): AccessToken
{
/** @var UserIdentityModel $identityModel */
$identityModel = model(UserIdentityModel::class);

return $identityModel->generateAccessToken($this, $name, $scopes);
return $identityModel->generateAccessToken($this, $name, $scopes, $expiresAt);
}

/**
Expand Down Expand Up @@ -165,4 +171,46 @@ public function setAccessToken(?AccessToken $accessToken): self

return $this;
}

/**
* Checks if the provided Access Token has expired.
*
* @return bool Returns true if Access Token has expired, false if not
*/
public function hasAccessTokenExpired(AccessToken $accessToken): bool
{
return $accessToken->expires !== null && $accessToken->expires->isBefore(Time::now());
}

/**
* Sets an expiration for Access Tokens by ID.
*
* @param int $id AccessTokens ID
* @param Time $expiresAt Expiration date
*
* @return bool Returns true if expiration date is set or updated.
*/
public function setAccessTokenExpirationById(int $id, Time $expiresAt): bool
{
/** @var UserIdentityModel $identityModel */
$identityModel = model(UserIdentityModel::class);
$result = $identityModel->setIdentityExpirationById($id, $this, $expiresAt, AccessTokens::ID_TYPE_ACCESS_TOKEN);

if ($result) {
// refresh currentAccessToken with updated data
$this->currentAccessToken = $identityModel->getAccessTokenById($id, $this);
}

return $result;
}

/**
* Checks if the current Hmac token can expire
*
* @return bool Returns true if AccessToken can expire.
*/
public function canAccessTokenExpire(AccessToken $accessToken): bool
{
return $accessToken->expires !== null;
}
}
55 changes: 51 additions & 4 deletions src/Authentication/Traits/HasHmacTokens.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,11 @@

namespace CodeIgniter\Shield\Authentication\Traits;

use CodeIgniter\I18n\Time;
use CodeIgniter\Shield\Authentication\Authenticators\HmacSha256;
use CodeIgniter\Shield\Entities\AccessToken;
use CodeIgniter\Shield\Models\UserIdentityModel;
use InvalidArgumentException;
use ReflectionException;

/**
Expand All @@ -35,17 +38,19 @@ trait HasHmacTokens
/**
* Generates a new personal HMAC token for this user.
*
* @param string $name Token name
* @param list<string> $scopes Permissions the token grants
* @param string $name Token name
* @param list<string> $scopes Permissions the token grants
* @param Time $expiresAt Expiration date
*
* @throws InvalidArgumentException
* @throws ReflectionException
*/
public function generateHmacToken(string $name, array $scopes = ['*']): AccessToken
public function generateHmacToken(string $name, array $scopes = ['*'], ?Time $expiresAt = null): AccessToken
{
/** @var UserIdentityModel $identityModel */
$identityModel = model(UserIdentityModel::class);

return $identityModel->generateHmacToken($this, $name, $scopes);
return $identityModel->generateHmacToken($this, $name, $scopes, $expiresAt);
}

/**
Expand Down Expand Up @@ -156,4 +161,46 @@ public function setHmacToken(?AccessToken $accessToken): self

return $this;
}

/**
* Checks if the provided Access Token has expired.
*
* @return bool Returns true if Access Token has expired, false if not
*/
public function hasHmacTokenExpired(AccessToken $accessToken): bool
{
return $accessToken->expires !== null && $accessToken->expires->isBefore(Time::now());
}

/**
* Sets an expiration for Hmac Key/Token by ID.
*
* @param int $id AccessToken ID
* @param Time $expiresAt Expiration date
*
* @return bool Returns true if expiration date is set or updated.
*/
public function setHmacTokenExpirationById(int $id, Time $expiresAt): bool
{
/** @var UserIdentityModel $identityModel */
$identityModel = model(UserIdentityModel::class);
$result = $identityModel->setIdentityExpirationById($id, $this, $expiresAt, HmacSha256::ID_TYPE_HMAC_TOKEN);

if ($result) {
// refresh currentAccessToken with updated data
$this->currentAccessToken = $identityModel->getHmacTokenById($id, $this);
}

return $result;
}

/**
* Checks if the current Hmac token can expire
*
* @return bool Returns true if Hmac Token can expire.
*/
public function canHmacTokenExpire(AccessToken $accessToken): bool
{
return $accessToken->expires !== null;
}
}
Loading
Loading