Формируем время в DateTime для генерации JWT токенов

This commit is contained in:
ErickSkrauch 2016-11-04 12:23:04 +03:00
parent 203d9c9fb4
commit c324ebe1c6
3 changed files with 23 additions and 8 deletions

View File

@ -3,6 +3,8 @@ namespace api\components\User;
use api\models\AccountIdentity; use api\models\AccountIdentity;
use common\models\AccountSession; use common\models\AccountSession;
use DateInterval;
use DateTime;
use Emarref\Jwt\Algorithm\AlgorithmInterface; use Emarref\Jwt\Algorithm\AlgorithmInterface;
use Emarref\Jwt\Algorithm\Hs256; use Emarref\Jwt\Algorithm\Hs256;
use Emarref\Jwt\Claim; use Emarref\Jwt\Claim;
@ -33,7 +35,9 @@ class Component extends YiiUserComponent {
public $secret; public $secret;
public $expirationTimeout = 3600; // 1h public $expirationTimeout = 'PT1H';
public $sessionTimeout = 'P7D';
public function init() { public function init() {
parent::init(); parent::init();
@ -73,7 +77,7 @@ class Component extends YiiUserComponent {
$session = null; $session = null;
// Если мы не сохраняем сессию, то токен должен жить подольше, чтобы // Если мы не сохраняем сессию, то токен должен жить подольше, чтобы
// не прогорала сессия во время работы с аккаунтом // не прогорала сессия во время работы с аккаунтом
$token->addClaim(new Claim\Expiration(time() + 60 * 60 * 24 * 7)); $token->addClaim(new Claim\Expiration((new DateTime())->add(new DateInterval($this->sessionTimeout))));
} }
$jwt = $this->serializeToken($token); $jwt = $this->serializeToken($token);
@ -135,8 +139,8 @@ class Component extends YiiUserComponent {
* - Юзер не авторизован * - Юзер не авторизован
* - Почему-то нет заголовка с токеном * - Почему-то нет заголовка с токеном
* - Во время проверки токена возникла ошибка, что привело к исключению * - Во время проверки токена возникла ошибка, что привело к исключению
* - В токене не найдено ключа сессии. Такое возможно, если юзер выбрал "не запоминать меня" или просто старые * - В токене не найдено ключа сессии. Такое возможно, если юзер выбрал "не запоминать меня"
* токены, без поддержки сохранения используемой сессии * или просто старые токены, без поддержки сохранения используемой сессии
* *
* @return AccountSession|null * @return AccountSession|null
*/ */
@ -187,14 +191,14 @@ class Component extends YiiUserComponent {
* @return Claim\AbstractClaim[] * @return Claim\AbstractClaim[]
*/ */
protected function getClaims(IdentityInterface $identity) { protected function getClaims(IdentityInterface $identity) {
$currentTime = time(); $currentTime = new DateTime();
$hostInfo = Yii::$app->request->hostInfo; $hostInfo = Yii::$app->request->hostInfo;
return [ return [
new Claim\Audience($hostInfo), new Claim\Audience($hostInfo),
new Claim\Issuer($hostInfo), new Claim\Issuer($hostInfo),
new Claim\IssuedAt($currentTime), new Claim\IssuedAt($currentTime),
new Claim\Expiration($currentTime + $this->expirationTimeout), new Claim\Expiration($currentTime->add(new DateInterval($this->expirationTimeout))),
new Claim\JwtId($identity->getId()), new Claim\JwtId($identity->getId()),
]; ];
} }

View File

@ -2,6 +2,8 @@
namespace api\components\User; namespace api\components\User;
use common\models\AccountSession; use common\models\AccountSession;
use DateInterval;
use DateTime;
use Yii; use Yii;
use yii\web\IdentityInterface; use yii\web\IdentityInterface;
@ -45,9 +47,13 @@ class LoginResult {
public function getAsResponse() { public function getAsResponse() {
/** @var Component $component */ /** @var Component $component */
$component = Yii::$app->user; $component = Yii::$app->user;
$now = new DateTime();
$expiresIn = (clone $now)->add(new DateInterval($component->expirationTimeout));
$response = [ $response = [
'access_token' => $this->getJwt(), 'access_token' => $this->getJwt(),
'expires_in' => $component->expirationTimeout, 'expires_in' => $expiresIn->getTimestamp() - $now->getTimestamp(),
]; ];
$session = $this->getSession(); $session = $this->getSession();

View File

@ -1,6 +1,8 @@
<?php <?php
namespace api\components\User; namespace api\components\User;
use DateInterval;
use DateTime;
use Yii; use Yii;
use yii\web\IdentityInterface; use yii\web\IdentityInterface;
@ -33,9 +35,12 @@ class RenewResult {
/** @var Component $component */ /** @var Component $component */
$component = Yii::$app->user; $component = Yii::$app->user;
$now = new DateTime();
$expiresIn = (clone $now)->add(new DateInterval($component->expirationTimeout));
return [ return [
'access_token' => $this->getJwt(), 'access_token' => $this->getJwt(),
'expires_in' => $component->expirationTimeout, 'expires_in' => $expiresIn->getTimestamp() - $now->getTimestamp(),
]; ];
} }