| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293 |
- <?php
- namespace mobile\controllers;
- use biz\user\services\UserService;
- use common\components\token;
- use Yii;
- use yii\db\Exception;
- use yii\web\Controller;
- use Lcobucci\JWT\Builder;
- use Lcobucci\JWT\Parser;
- use Lcobucci\JWT\ValidationData;
- use Lcobucci\JWT\Signer\Key;
- use Lcobucci\JWT\Signer\Hmac\Sha256;
- class MainController extends PublicController
- {
-
- public $enableCsrfValidation = false;
-
- public function actionIndex()
- {
- $host = Yii::$app->request->getHostInfo();
- $fullUrl = Yii::$app->request->url;
- $token = strpos($fullUrl, 'token') === false ? '' : 'hasToken';
- return $this->renderPartial('index', ['host' => $host, 'token' => $token]);
- }
-
- public function actionJwt()
- {
- $time = time();
- $signer = new Sha256();
- $key = new Key('testing');
- $token = (new Builder())->issuedBy('http://example.com')//发布者的url地址
-
- ->canOnlyBeUsedBy('http://example.org')//接受者的url地址
- ->identifiedBy('12358', true)//该jwt的唯一ID编号
- ->issuedAt($time)//该jwt的发布时间
- ->canOnlyBeUsedAfter($time + 60)//该jwt的使用时间不能早于该时间
- ->expiresAt($time + 3600)//该jwt销毁的时间
- ->with('uid', 1)
- ->set('username', 'lili')//设置一个变量
- ->sign($signer, $key)//设置一个变量,同set
- ->getToken();
- echo '<pre>';
- echo $token;
-
- echo '<br />';
- $token->getHeaders(); // Retrieves the token headers
- $token->getClaims(); // Retrieves the token claims
- echo '<br />';
- echo $token->getHeader('jti'); // will print "4f1g23a12aa"
- echo '<br />';
- echo $token->getClaim('iss'); // will print "http://example.com"
-
- $token = (new Parser())->parse((string)'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiIsImp0aSI6IjEyMzU4In0.eyJpc3MiOiJodHRwOlwvXC9leGFtcGxlLmNvbSIsImF1ZCI6Imh0dHA6XC9cL2V4YW1wbGUub3JnIiwianRpIjoiMTIzNTgiLCJpYXQiOjE1NzQzNDk5OTYsIm5iZiI6MTU3NDM1MDA1NiwiZXhwIjoxNTc0MzUzNTk2LCJ1aWQiOjF9.6FtTHmMlqhI1BNoFJiJrmm1nXXtc5-u2tVt-A8s8IN8
- ');
-
- $token->getHeaders(); // Retrieves the token header
- $token->getClaims(); // Retrieves the token claims
- echo "<br />....<br />";
- echo $token->getHeader('jti'); // will print "4f1g23a12aa"
- echo '<br />';
- echo $token->getClaim('iss'); // will print "http://example.com"
- echo '<br />';
- echo $token->getClaim('uid'); // will print "1"
- echo '<br />';
-
- $data = new ValidationData(); // It will use the current time to validate (iat, nbf and exp)
-
- $data->setIssuer('http://example.com');
- $data->setAudience('http://example.org');
- $data->setId('12358');
-
- //先验证私钥
- var_dump($token->verify($signer, $key));
-
- //失败,因为token在60秒后方可验证
- var_dump($token->validate($data));
-
- $data->setCurrentTime($time + 61); // changing the validation time to future
-
- // true
- var_dump($token->validate($data));
-
- $data->setCurrentTime(time() + 4000);
- //false,token过期
- var_dump($token->validate($data));
-
- }
-
- }
|