如何在Yii2项目中使用JWT?

时间:2017-05-31 10:11:44

标签: yii2 jwt

在我的REST API中,我想使用授权的JWT。

所以,我添加了此扩展程序 - https://github.com/sizeg/yii2-jwt

它清楚如何创建JWT令牌,但如何在API端验证令牌?我心里,我必须使用两个令牌 - auth_token和refresh_token。为了什么?当我需要验证并检查用户时会有什么不同?

我的意思是 - 好吧,当我收到用户名和密码时,我在将令牌返回前端后,在用户数据库中创建auth_token(JWT)并更新令牌。

前端将在每个请求中发送身份验证令牌,我将验证令牌并检查用户数据库中的用户并检查访问权限等。如何实现刷新令牌以及为什么?

例如我的控制器:

class UploadController extends Controller {

    public $serializer = [
        'class' => 'yii\rest\Serializer',
        'collectionEnvelope' => 'items',
    ];

    public function behaviors()
    {
        $behaviors = parent::behaviors();

        $behaviors['authenticator'] = [
            'class' => JwtHttpBearerAuth::className()
        ];

        return $behaviors;
    }

    public function actionIndex() {

       //Work with User
    }
}

如何从标头中获取令牌?

1 个答案:

答案 0 :(得分:4)

控制器

public function actionLogin()
{

    $username = Yii::$app->request->post('username');
    $password = Yii::$app->request->post('password');

    $provider = new ActiveDataProvider([
        'query' => User::find()
                ->where(['user_name' => $username])->asArray()->one(),
    ]);

    $result = $provider->query;

    if($result)
    {
        if (Yii::$app->getSecurity()->validatePassword($password, $result['user_pass'])) 
        {
            $tokenId    = base64_encode(mcrypt_create_iv(32));
            $issuedAt   = time();
            $notBefore  = $issuedAt;             //Adding 10 seconds
            $expire     = $notBefore + 5184000;            // Adding 60 Days
            $serverName = 'your-site.com';
            $data = [
                'iat'  => $issuedAt,         // Issued at: time when the token was generated
                'jti'  => $tokenId,          // Json Token Id: an unique identifier for the token
                'iss'  => $serverName,       // Issuer
                'nbf'  => $notBefore,        // Not before
                'exp'  => $expire,           // Expire
                'data' => [                  // Data related to the signer user
                    'id' => $result['user_id'],
                    'username' => $result['user_name'],
                    'mobile' => $result['user_mobile'],
                    'email' => $result['user_email'],
                    'city' => $result['user_city'],
                    'state' => $result['user_state'],
                    'country' => $result['user_country'],
                    'picture' => $result['user_picture'],
                ]
            ];

            $jwt = JWT::encode(
                $data,     
                JWT_KEY, 
                'HS512'  
            );

            $response = [
                'status' => true,
                'message' => 'Login Success..',
                'era_tkn' => $jwt,
            ];
        } 
        else 
        {
            $response = [
                'status' => false,
                'message' => 'Wrong username or password.',
            ];
        }
    }
    else
    {
        $response = [
            'status' => false,
            'message' => 'Wrong username or password.',
        ];
    }

    return $response;
}

制作检查令牌的全局方法

public function check_token()
{
    $headers = Yii::$app->request->headers;
    $token = $headers->get('era_tkn');
    if($token)
    {
        try{
        $valid_data = JWT::decode($token, JWT_KEY, array('HS512'));
        $valid_data = $valid_data->data;

        }catch(Exception $e){
            $valid_data = $e->getMessage();
        }
    }
    else
    {
        $valid_data = 'Required Authentication';
    }

    return $valid_data;
}

调用check_token mathod

$user_data = $this->check_token();
    if (!empty($user_data->id))
    {
        echo $user_data->id;
    }
    else
    {
       echo "Invalid Token.";
    }