Home > Backend Development > PHP Tutorial > Detailed explanation of restful api authorization verification of yii2

Detailed explanation of restful api authorization verification of yii2

*文
Release: 2023-03-19 07:16:02
Original
3054 people have browsed it

This article mainly introduces to you the relevant information about the actual restful api authorization verification of the yii2 project. The introduction in the article is very detailed and has a certain reference and learning value for everyone. Friends who need it can take a look below. I hope to be helpful.

Preface

This article is mainly written for the deployment of APIs in actual scenarios.

Today we are going to talk about the authorization verification problems encountered by the API in those years!

Business Analysis

Let’s first understand the entire logic

  • The user fills in the client Login form

  • The user submits the form, and the client requests the login interface login

  • The server verifies the user's account password and returns a valid Token to client

  • The client gets the user's token and stores it in the client such as a cookie

  • The client carries the token to access Interfaces that need to be verified, such as the interface for obtaining user personal information

  • The server verifies the validity of the token, and the verification passes. Anyway, the information required by the client is returned. If the verification fails, the user is required Log in again

#In this article, we take the user login and obtain the user's personal information as an example to give a detailed and complete explanation.
The above is the focus of this article. Don't get excited or nervous yet. After analyzing it, we will proceed step by step with the details.

Preparation

  • You should have an api application

  • For the client, we are going to use postman for simulation. If your Google browser has not installed postman, please download it yourself first

  • The user table to be tested needs to have an api_token If there is no field, please add it yourself first, and ensure that the field is long enough

  • The api application enables route beautification, and first configure the post type login operation and the get type signup-test Operation

  • Close the session session of the user component

Regarding points 4 and 5 of the above preparations, we will post The following code is easy to understand

'components' => [
 'user' => [ 
 'identityClass' => 'common\models\User',
 'enableAutoLogin' => true,
 'enableSession' => false,
 ],
 'urlManager' => [
 'enablePrettyUrl' => true,
 'showScriptName' => false,
 'enableStrictParsing' => true,
 'rules' => [
  [
  'class' => 'yii\rest\UrlRule',
  'controller' => ['v1/user'],
  'extraPatterns' => [
   'POST login' => 'login',
   'GET signup-test' => 'signup-test',
  ]
  ],
 ]
 ],
 // ......
],
Copy after login

signup-test operation. We will add a test user later to facilitate the login operation. Other types of operations will need to be added later.

Selection of authentication class

We set it in api\modules\v1\controllers\UserController The certain model class points to the common\models\User class. In order to illustrate the key points, we will not rewrite it separately. Depending on your needs, if necessary, copy a separate User class to the api. \modelsDown.

To verify user permissions, we take yii\filters\auth\QueryParamAuth as an example

use yii\filters\auth\QueryParamAuth;

public function behaviors() 
{
 return ArrayHelper::merge (parent::behaviors(), [ 
  'authenticator' => [ 
  'class' => QueryParamAuth::className() 
  ] 
 ] );
}
Copy after login

In this case, wouldn’t all operations that access the user be valid? Need certification? That doesn't work. Where does the token come from when the client first accesses the login operation? yii\filters\auth\QueryParamAuth provides an external attribute for filtering actions that do not require verification. We slightly modify the behaviors method of UserController

public function behaviors() 
{
 return ArrayHelper::merge (parent::behaviors(), [ 
  'authenticator' => [ 
  'class' => QueryParamAuth::className(),
  'optional' => [
   'login',
   'signup-test'
  ],
  ] 
 ] );
}
Copy after login

so that the login operation can be accessed without permission verification.

Add test user

#In order to avoid client login failure, we first write a simple method to add it to the user table Insert two pieces of data to facilitate subsequent verification.

UserController adds signupTest operation. Note that this method is not within the scope of explanation. We only use it to facilitate testing.

use common\models\User;
/**
 * 添加测试用户
 */
public function actionSignupTest ()
{
 $user = new User();
 $user->generateAuthKey();
 $user->setPassword('123456');
 $user->username = '111';
 $user->email = '111@111.com';
 $user->save(false);

 return [
 'code' => 0
 ];
}
Copy after login

As above, we added a user with username 111 and password 123456

Login operation

Assume that the user enters the username and password on the client to log in. The server-side login operation is actually very simple. Most of the business logic processing is done on api\models\loginForm. Let’s first take a look at the implementation of login

use api\models\LoginForm;

/**
 * 登录
 */
public function actionLogin ()
{
 $model = new LoginForm;
 $model->setAttributes(Yii::$app->request->post());
 if ($user = $model->login()) {
 if ($user instanceof IdentityInterface) {
  return $user->api_token;
 } else {
  return $user->errors;
 }
 } else {
 return $model->errors;
 }
}
Copy after login

After successful login, the user's token is returned to the client. Let's take a look at the implementation of the specific login logic

Create a new api\models\LoginForm.PHP

<?php
namespace api\models;

use Yii;
use yii\base\Model;
use common\models\User;

/**
 * Login form
 */
class LoginForm extends Model
{
 public $username;
 public $password;

 private $_user;

 const GET_API_TOKEN = &#39;generate_api_token&#39;;

 public function init ()
 {
 parent::init();
 $this->on(self::GET_API_TOKEN, [$this, &#39;onGenerateApiToken&#39;]);
 }


 /**
 * @inheritdoc
 * 对客户端表单数据进行验证的rule
 */
 public function rules()
 {
 return [
  [[&#39;username&#39;, &#39;password&#39;], &#39;required&#39;],
  [&#39;password&#39;, &#39;validatePassword&#39;],
 ];
 }

 /**
 * 自定义的密码认证方法
 */
 public function validatePassword($attribute, $params)
 {
 if (!$this->hasErrors()) {
  $this->_user = $this->getUser();
  if (!$this->_user || !$this->_user->validatePassword($this->password)) {
  $this->addError($attribute, &#39;用户名或密码错误.&#39;);
  }
 }
 }
 /**
 * @inheritdoc
 */
 public function attributeLabels()
 {
 return [
  &#39;username&#39; => &#39;用户名&#39;,
  &#39;password&#39; => &#39;密码&#39;,
 ];
 }
 /**
 * Logs in a user using the provided username and password.
 *
 * @return boolean whether the user is logged in successfully
 */
 public function login()
 {
 if ($this->validate()) {
  $this->trigger(self::GET_API_TOKEN);
  return $this->_user;
 } else {
  return null;
 }
 }

 /**
 * 根据用户名获取用户的认证信息
 *
 * @return User|null
 */
 protected function getUser()
 {
 if ($this->_user === null) {
  $this->_user = User::findByUsername($this->username);
 }

 return $this->_user;
 }

 /**
 * 登录校验成功后,为用户生成新的token
 * 如果token失效,则重新生成token
 */
 public function onGenerateApiToken ()
 {
 if (!User::apiTokenIsValid($this->_user->api_token)) {
  $this->_user->generateApiToken();
  $this->_user->save(false);
 }
 }
}
Copy after login

Let’s look back and see what happened when we called the login operation of LoginForm in the login operation of UserController

1 , call the login method of LoginForm

2. Call the validate method, and then verify the rules

3. Call the validatePassword method in rules verification to verify the user name and password

4. During the validation process of the validatePassword method, call the getUser method of LoginForm and obtain the user through findByUsername of the common\models\User class. If it cannot be found or common\models\UservalidatePassword returns error if it fails to verify the password

5、触发LoginForm::GENERATE_API_TOKEN事件,调用LoginForm的onGenerateApiToken方法,通过common\models\User的apiTokenIsValid校验token的有效性,如果无效,则调用User的generateApiToken方法重新生成

注意:common\models\User类必须是用户的认证类,如果不知道如何创建完善该类,请围观这里 用户管理之user组件的配置

下面补充本节增加的common\models\User的相关方法

/**
 * 生成 api_token
 */
public function generateApiToken()
{
 $this->api_token = Yii::$app->security->generateRandomString() . &#39;_&#39; . time();
}

/**
 * 校验api_token是否有效
 */
public static function apiTokenIsValid($token)
{
 if (empty($token)) {
 return false;
 }

 $timestamp = (int) substr($token, strrpos($token, &#39;_&#39;) + 1);
 $expire = Yii::$app->params[&#39;user.apiTokenExpire&#39;];
 return $timestamp + $expire >= time();
}
Copy after login

继续补充apiTokenIsValid方法中涉及到的token有效期,在api\config\params.php文件内增加即可

<?php
return [
 // ...
 // token 有效期默认1天
 &#39;user.apiTokenExpire&#39; => 1*24*3600,
];
Copy after login

到这里呢,客户端登录 服务端返回token给客户端就完成了。

按照文中一开始的分析,客户端应该把获取到的token存到本地,比如cookie中。以后再需要token校验的接口访问中,从本地读取比如从cookie中读取并访问接口即可。

根据token请求用户的认证操作

假设我们已经把获取到的token保存起来了,我们再以访问用户信息的接口为例。

yii\filters\auth\QueryParamAuth类认定的token参数是 access-token,我们可以在行为中修改下

public function behaviors() 
{
 return ArrayHelper::merge (parent::behaviors(), [ 
   &#39;authenticator&#39; => [ 
    &#39;class&#39; => QueryParamAuth::className(),
    &#39;tokenParam&#39; => &#39;token&#39;,
    &#39;optional&#39; => [
     &#39;login&#39;,
     &#39;signup-test&#39;
    ],
   ] 
 ] );
}
Copy after login

这里将默认的access-token修改为token。

我们在配置文件的urlManager组件中增加对userProfile操作

&#39;extraPatterns&#39; => [
 &#39;POST login&#39; => &#39;login&#39;,
 &#39;GET signup-test&#39; => &#39;signup-test&#39;,
 &#39;GET user-profile&#39; => &#39;user-profile&#39;,
]
Copy after login

我们用postman模拟请求访问下 /v1/users/user-profile?token=apeuT9dAgH072qbfrtihfzL6qDe_l4qz_1479626145发现,抛出了一个异常

\"findIdentityByAccessToken\" is not implemented.<br/>

这是怎么回事呢?

我们找到 yii\filters\auth\QueryParamAuth 的authenticate方法,发现这里调用了 common\models\User类的loginByAccessToken方法,有同学疑惑了,common\models\User类没实现loginByAccessToken方法为啥说findIdentityByAccessToken方法没实现?如果你还记得common\models\User类实现了yii\web\user类的接口的话,你应该会打开yii\web\User类找答案。没错,loginByAccessToken方法在yii\web\User中实现了,该类中调用了common\models\User的findIdentityByAccessToken,但是我们看到,该方法中通过throw抛出了异常,也就是说这个方法要我们自己手动实现!

这好办了,我们就来实现下common\models\User类的findIdentityByAccessToken方法吧

public static function findIdentityByAccessToken($token, $type = null)
{
 // 如果token无效的话,
 if(!static::apiTokenIsValid($token)) {
  throw new \yii\web\UnauthorizedHttpException("token is invalid.");
 }

 return static::findOne([&#39;api_token&#39; => $token, &#39;status&#39; => self::STATUS_ACTIVE]);
 // throw new NotSupportedException(&#39;"findIdentityByAccessToken" is not implemented.&#39;);
}
Copy after login

验证完token的有效性,下面就要开始实现主要的业务逻辑部分了。

/**
 * 获取用户信息
 */
public function actionUserProfile ($token)
{
 // 到这一步,token都认为是有效的了
 // 下面只需要实现业务逻辑即可,下面仅仅作为案例,比如你可能需要关联其他表获取用户信息等等
 $user = User::findIdentityByAccessToken($token);
 return [
  &#39;id&#39; => $user->id,
  &#39;username&#39; => $user->username,
  &#39;email&#39; => $user->email,
 ];
}
Copy after login

服务端返回的数据类型定义

在postman中我们可以以何种数据类型输出的接口的数据,但是,有些人发现,当我们把postman模拟请求的地址copy到浏览器地址栏,返回的又却是xml格式了,而且我们明明在UserProfile操作中返回的是属组,怎么回事呢?

这其实是官方捣的鬼啦,我们一层层源码追下去,发现在yii\rest\Controller类中,有一个 contentNegotiator行为,该行为指定了允许返回的数据格式formats是json和xml,返回的最终的数据格式根据请求头中Accept包含的首先出现在formats中的为准,你可以在yii\filters\ContentNegotiatornegotiateContentType方法中找到答案。

你可以在浏览器的请求头中看到

Accept:

text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8

即application/xml首先出现在formats中,所以返回的数据格式是xml类型,如果客户端获取到的数据格式想按照json进行解析,只需要设置请求头的Accept的值等于application/json即可

有同学可能要说,这样太麻烦了,啥年代了,谁还用xml,我就想服务端输出json格式的数据,怎么做?

办法就是用来解决问题滴,来看看怎么做。api\config\main.php文件中增加对response的配置

&#39;response&#39; => [
 &#39;class&#39; => &#39;yii\web\Response&#39;,
 &#39;on beforeSend&#39; => function ($event) {
  $response = $event->sender;
  $response->format = yii\web\Response::FORMAT_JSON;
 },
],
Copy after login

如此,不管你客户端传什么,服务端最终输出的都会是json格式的数据了。

自定义错误处理机制

再来看另外一个比较常见的问题:

你看我们上面几个方法哈,返回的结果是各式各样的,这样就给客户端解析增加了困扰,而且一旦有异常抛出,返回的代码还都是一堆一堆的,头疼,怎么办?

说到这个问题之前呢,我们先说一下yii中先关的异常处理类,当然,有很多哈。比如下面常见的一些,其他的自己去挖掘

yii\web\BadRequestHttpException
yii\web\ForbiddenHttpException
yii\web\NotFoundHttpException
yii\web\ServerErrorHttpException
yii\web\UnauthorizedHttpException
yii\web\TooManyRequestsHttpException
Copy after login

实际开发中各位要善于去利用这些类去捕获异常,抛出异常。说远了哈,我们回到重点,来说如何自定义接口异常响应或者叫自定义统一的数据格式,比如向下面这种配置,统一响应客户端的格式标准。

&#39;response&#39; => [
 &#39;class&#39; => &#39;yii\web\Response&#39;,
 &#39;on beforeSend&#39; => function ($event) {
  $response = $event->sender;
  $response->data = [
   &#39;code&#39; => $response->getStatusCode(),
   &#39;data&#39; => $response->data,
   &#39;message&#39; => $response->statusText
  ];
  $response->format = yii\web\Response::FORMAT_JSON;
 },
],
Copy after login

说道了那么多,本文就要结束了,刚开始接触的同学可能有一些蒙,不要蒙,慢慢消化,先知道这么个意思,了解下restful api接口在整个过程中是怎么用token授权的就好。这样真正实际用到的时候,你也能举一反三!

相关推荐:

Yii2整合迅搜实现高效中文分词检索

Yii如何过滤不良代码

Yii2实现rbac权限控制

The above is the detailed content of Detailed explanation of restful api authorization verification of yii2. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template