Yii2 REST 简化 BasicAuth [英] Yii2 REST Simplify BasicAuth

查看:27
本文介绍了Yii2 REST 简化 BasicAuth的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Yii2 中创建 REST api 是多么简单,这给我留下了深刻的印象.但是,我在理解基本身份验证时遇到了一些麻烦.我的需求非常简单,我希望我的解决方案也能效仿.

I'm impressed with how simple it was to create a REST api in Yii2. However, i'm having a little trouble understanding the Basic Authentication. My needs are utterly simple and i'd like my solution to follow suit.

我需要在这里进行基本令牌身份验证.我现在什至不反对硬编码,但这是我迄今为止所做的.

I need Basic token authentication here. I'm not even against hardcoding it for now, but here's what i've done thus far.

我有数据库表来保存我的单一令牌 ApiAccess(id, access_token)

I have database table to hold my singular token ApiAccess(id, access_token)

ApiAccess.php - 模型 - 注意:IDE 在第一行显示语法错误

ApiAccess.php - Model - NOTE: IDE shows syntax error on this first line

 class ApiAccess extends base\ApiAccessBase implements IdentityInterface
 {
   public static function findIdentityByAccessToken($token, $type = null)
   {
     return static::findOne(['access_token' => $token]);
   }
 }

Module.php - 在 init() 函数中

Module.php - in init() function

 \Yii::$app->user->enableSession = false;

我制作了一个 ApiController,每个后续名词都扩展了

I made an ApiController that each subsequent noun extends

ApiController.php

 use yii\rest\ActiveController;
 use yii\filters\auth\HttpBasicAuth;
 use app\models\db\ApiAccess;

 class ApiController extends ActiveController
 {
   public function behaviors()
   {
      $behaviors = parent::behaviors();
      $behaviors['authenticator'] = [
        'class' => HttpBasicAuth::className(),
      ];
     return $behaviors;
   }
 }

就目前而言,在浏览器中访问 api 端点会提示输入用户名和密码.通过 REST 客户端的请求显示访问错误.

As it stands, accessing an api endpoint in the browser prompts for a username and password. Request via REST Client displays access error.

如何将 HttpBasicAuth 正确绑定到我的 ApiAccess 模型?

如何对 api 访问令牌进行硬编码?(第一个选项显然是最好的)

How do I hardcode an api access token? (First option is obviously best)

推荐答案

让我们观察并尝试理解yii"方式的 REST 基本身份验证.

Let's watch and try to understand "yii" way basic auth for REST.

第一.当您向 REST 控制器添加行为时,您将启用基本身份验证:

1st. When you adding behavior to your REST controller, you enabling basic auth:

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

正如你所做的那样.这是什么意思?这意味着您的应用程序将解析您的授权标头.它看起来像:

As you did. What does it mean? It means that your application will parse your authorization header. It looks like:

Authorization : Basic base64(user:password)

这是 yii2 的一个技巧.如果您更仔细地查看代码,您会看到 yii 使用了来自用户字段的 access_token,因此您的标题应该如下所示:

Here is a trick for yii2. If you look at code more carefully, you will see that yii uses access_token from user field, so your header should look like:

Authorization : Basic base64(access_token:)

如果你想改变这个行为,你可以自己解析这个头:

You can parse this header by your own, if you want to change this behavior:

$behaviors['authenticator'] = [
            'class' => HttpBasicAuth::className(),
            'auth' => [$this, 'auth']
        ];
....
public function auth($username, $password)
    {
        return \app\models\User::findOne(['login' => $username, 'password' => $password]);
    }

要做的第二件事.您必须从 identityInterface 实现 findIdentityByAccessToken() 函数.为什么您的 IDE 会抱怨?

2nd thing to do. You must implement findIdentityByAccessToken() function from identityInterface. Why your IDE complaining?

class User extends ActiveRecord implements IdentityInterface

您的用户类声明应如下所示.

Here's how your user class declaration should look.

来自您的实施和结构:

public static function findIdentityByAccessToken($token, $type = null)
   {
     return static::findOne(['access_token' => $token]);
   }

您没有返回实现身份接口的类的对象.

you not returning object of class which implements identity interface.

如何正确制作?将列 access_token 添加到您的用户表中,并返回您的用户模型(您可以在此处查看它的外观 - https://github.com/yiisoft/yii2-app-advanced/blob/master/common/models/User.php)如果您这样做 - 默认代码将与您的 findIdentityByAccessToken() 实现一起使用.

How to make it properly? Add column access_token to your users table, and return back your user model (you can look how it must look here - https://github.com/yiisoft/yii2-app-advanced/blob/master/common/models/User.php) If you do this - default code will work with your findIdentityByAccessToken() implementation.

如果您不想向用户表中添加字段 - 使用 user_id,access_token 字段创建一个新字段.那么你的实现应该是这样的:

If you don't want to add field to users table - make new one with user_id,access_token fields. Then your implementation should look like:

public static function findIdentityByAccessToken($token, $type = null)
   {
     $apiUser = ApiAccess::find()
        ->where(['access_token' => $token])
        ->one();
     return static::findOne(['id' => $apiUser->user_id, 'status' => self::STATUS_ACTIVE]);
   }

希望我能解答你所有的问题.

Hope i could cover all of your questions.

这篇关于Yii2 REST 简化 BasicAuth的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆