Code Monkey home page Code Monkey logo

Comments (11)

sizeg avatar sizeg commented on August 25, 2024 2

@bologer

  1. You check client credentials as usual. For example client send you simple login+password pair.
  2. After u validate his credentials you may generate JWT and send back it with response to client and store it
  3. 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

  1. Create application for example basic
    composer create-project --prefer-dist --stability=dev yiisoft/yii2-app-basic yii2-jwt-test
  2. Install jwt component
    composer require sizeg/yii2-jwt
  3. Add to config/web.php into components section
$config = [
    'components' => [
        // other default components here..
        'jwt' => [
            'class' => 'sizeg\jwt\Jwt',
            'key'   => 'secret',
        ],
    ],
];
  1. 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;
    }
  1. 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,
        ]);
    }
}
  1. Send simple login request to get token. Here we does not send any credentials to simplify example. As we specify in authenticator behavior action login as optional the authenticator skip auth check for that action.
    image
  2. First of all we try to send request to rest/data without token and getting error Unauthorized
    image
  3. Then we retry request but already adding Authorization header with our token
    image

from yii2-jwt.

bologer avatar bologer commented on August 25, 2024 2

@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.

Den2016 avatar Den2016 commented on August 25, 2024 2

@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.

sizeg avatar sizeg commented on August 25, 2024 1

@bologer I've just update readme. You are welcome 👍

from yii2-jwt.

sizeg avatar sizeg commented on August 25, 2024

How do you send token?

from yii2-jwt.

jonatasfl avatar jonatasfl commented on August 25, 2024

@sizeg I'm sending the header Authorization: Bearer MY_TOKEN
capturar

Thank you!

from yii2-jwt.

jonatasfl avatar jonatasfl commented on August 25, 2024

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.

bologer avatar bologer commented on August 25, 2024

@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.

bologer avatar bologer commented on August 25, 2024

@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.

ebinmanuval avatar ebinmanuval commented on August 25, 2024

I am geting an exception Access to undeclared static property: api\models\User::$users

image

from yii2-jwt.

racielbd avatar racielbd commented on August 25, 2024

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)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo 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.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.