Comments (11)
- You check client credentials as usual. For example client send you simple login+password pair.
- After u validate his credentials you may generate JWT and send back it with response to client and store it
- Then you may authenticate with JWT. You should send it in request header
Authorization
.
I've just check making all this steps and provide you example
- Create application for example basic
composer create-project --prefer-dist --stability=dev yiisoft/yii2-app-basic yii2-jwt-test
- Install jwt component
composer require sizeg/yii2-jwt
- Add to config/web.php into
components
section
$config = [
'components' => [
// other default components here..
'jwt' => [
'class' => 'sizeg\jwt\Jwt',
'key' => 'secret',
],
],
];
- Change method
app\models\User::findIdentityByAccessToken()
/**
* {@inheritdoc}
* @param \Lcobucci\JWT\Token $token
*/
public static function findIdentityByAccessToken($token, $type = null)
{
foreach (self::$users as $user) {
if ($user['id'] === (string) $token->getClaim('uid')) {
return new static($user);
}
}
return null;
}
- Create controller for test
<?php
namespace app\controllers;
use sizeg\jwt\Jwt;
use sizeg\jwt\JwtHttpBearerAuth;
use Yii;
use yii\rest\Controller;
class RestController extends Controller
{
/**
* @inheritdoc
*/
public function behaviors()
{
$behaviors = parent::behaviors();
$behaviors['authenticator'] = [
'class' => JwtHttpBearerAuth::class,
'optional' => [
'login',
],
];
return $behaviors;
}
/**
* @return \yii\web\Response
*/
public function actionLogin()
{
// here you can put some credentials validation logic
// so if it success we return token
$signer = new \Lcobucci\JWT\Signer\Hmac\Sha256();
/** @var Jwt $jwt */
$jwt = Yii::$app->jwt;
$token = $jwt->getBuilder()
->setIssuer('http://example.com')// Configures the issuer (iss claim)
->setAudience('http://example.org')// Configures the audience (aud claim)
->setId('4f1g23a12aa', true)// Configures the id (jti claim), replicating as a header item
->setIssuedAt(time())// Configures the time that the token was issue (iat claim)
->setExpiration(time() + 3600)// Configures the expiration time of the token (exp claim)
->set('uid', 100)// Configures a new claim, called "uid"
->sign($signer, $jwt->key)// creates a signature using [[Jwt::$key]]
->getToken(); // Retrieves the generated token
return $this->asJson([
'token' => (string)$token,
]);
}
/**
* @return \yii\web\Response
*/
public function actionData()
{
return $this->asJson([
'success' => true,
]);
}
}
- Send simple login request to get token. Here we does not send any credentials to simplify example. As we specify in
authenticator
behavior actionlogin
as optional theauthenticator
skip auth check for that action.
- First of all we try to send request to rest/data without token and getting error
Unauthorized
- Then we retry request but already adding
Authorization
header with our token
from yii2-jwt.
@ebinmanuval it seems you are using basic template and you probably deleted static property on User
model. It is a mock array of users used to authenticate users. You should change all of the methods which depend on $users
static property ot database ActiveRecord or just revert static propert back.
from yii2-jwt.
@ebinmanuval it seems you are using basic template and you probably deleted static property on
User
model. It is a mock array of users used to authenticate users. You should change all of the methods which depend on$users
static property ot database ActiveRecord or just revert static propert back.
Ну у меня на свежем advanced то же самое получилось. Сам свойство не удалял, его просто не было. Переделал на более простой вариант
public static function findIdentityByAccessToken($token, $type = null)
{
return self::findIdentity($token->getClaim('uid'));
}
findIdentity лежит прям рядом, ищет пользователя по id, возвращает то, что надо ))
Использую Apache 2.4, PHP 7.2
from yii2-jwt.
@bologer I've just update readme. You are welcome 👍
from yii2-jwt.
How do you send token?
from yii2-jwt.
@sizeg I'm sending the header Authorization: Bearer MY_TOKEN
Thank you!
from yii2-jwt.
I found a solution...
In my Controllers I need to change the authenticator behavior from JwtHttpBearerAuth::className()
to HttpBearerAuth::className()
(Yii2 native)
In User Model I need to implement the findIdentityByAccessToken method as follow:
public static function findIdentityByAccessToken($token, $type = null)
{
$token = \Yii::$app->jwt->getParser()->parse((string) $token); // Parses from a string
$signer = new Sha256();
$data = \Yii::$app->jwt->getValidationData(); // It will use the current time to validate (iat, nbf and exp)
$data->setIssuer('http://myurl');
$data->setAudience('http://myurl');
$data->setId('myid');
$username = $data->getClaim('username');
if ($token->validate($data) && $token->verify($signer, 'testing')) {
return static::findByUsername($username);
}
return null;
}
from yii2-jwt.
@sizeg btw, why did JwtHttpBearerAuth::className()
not work ? This is strange. I am also having the same issue. Placing break point at init() of JwtHttpBearerAuth::className()
and get nothing. HttpBearerAuth::className()
seems to be ok.
public function behaviors()
{
$behaviors = parent::behaviors();
$behaviors['authenticator'] = [
'class' => JwtHttpBearerAuth::class,
];
return $behaviors;
}
Could you briefly explain the work flow? Or maybe provide some example in the README.
My case:
I have React app and I would like to use Yii2 as backend.
I assume the flow should be following:
I should have LoginController to have authentication endpoint to generate and save JWT for user. On success I place cookie on user side and every further request should be adding authentication header with the JWT token.
Is it correct?
from yii2-jwt.
@sizeg wow, thank you for in-depth explanation!
What do you think about putting this in the Wiki? I think it could be useful to many people who cross similar issue as me. Also I crossed this article after you replied which explains it nicely as well.
from yii2-jwt.
I am geting an exception Access to undeclared static property: api\models\User::$users
from yii2-jwt.
Hi i know this issue is cloused but i still got a problem.., and i think you can help me here is the issue link #23
Thanks in advance...
from yii2-jwt.
Related Issues (20)
- JwtHttpBearerAuth not checking iss/aud HOT 2
- Problem with Claim uid HOT 1
- Optional login action HOT 3
- have cors origin problem when use authenticator HOT 3
- license unspecified HOT 1
- This token library can't invalidate or force to expire HOT 2
- How to increase the JWT Token Expiry Time? HOT 1
- Support of lcobucci/jwt 3.4 HOT 4
- php8兼容问题 HOT 1
- Support PHP 8 HOT 5
- How change identity class: eg using Members instead Users HOT 1
- It is not supporting php 8.1 HOT 8
- Upgrade lcobucci/jwt package to 4.X HOT 2
- Returns error code 500 instead of 401 when token is expired HOT 1
- Setting unknown property: sizeg\\jwt\\Jwt::jwtValidationData HOT 4
- "Calling unknown method: sizeg\\jwt\\Jwt::decode()",
- CORS для refresh-token HOT 1
- PHP 8.1 Compatibility | Return Type Change for Lcobucci\JWT\Claim\Basic::jsonSerialize()
- Check expired token HOT 1
- Setting unknown property: sizeg\jwt\Jwt::key HOT 1
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from yii2-jwt.