转 http://www.yiichina.com/tutorial/1143
yii2中restful url访问配置, 登陆接口access-token验证类 [ 2.0 版本 ] 登陆接口access-token验证类
Controller下新建BaseActiveController.php <?php
/**
*接口登陆验证
* @author 爱博
* 1.0
*
*/
namespace backend\controllers; use yii\filters\auth\CompositeAuth;
use yii\filters\auth\HttpBasicAuth;
use yii\filters\auth\HttpBearerAuth;
use yii\filters\auth\QueryParamAuth;
use yii\filters\Cors;
use yii\filters\RateLimiter;
use yii\rest\Controller;
use Yii; class BaseActiveController extends Controller
{
public $modelClass = 'common\models\user'; public $post = null;
public $get = null;
public $user = null;
public $userId = null; public function init()
{
parent::init(); Yii::$app->user->enableSession = false;
} public function behaviors()
{
$behaviors = parent::behaviors(); $behaviors['authenticator'] = [
'class' => CompositeAuth::className(),
'authMethods' => [
// HttpBasicAuth::className(),
// HttpBearerAuth::className(),
QueryParamAuth::className(),
],
]; // 数据返回类型设置
//$behaviors['contentNegotiator']['formats']['application/json'] = 'json';
//$behaviors['contentNegotiator']['formats']['application/xml'] = 'json'; return $behaviors;
} public function beforeAction($action)
{
parent::beforeAction($action); $this->post = yii::$app->request->post();
$this->get = yii::$app->request->get();
$this->user = yii::$app->user->identity;
$this->userId = Yii::$app->user->id; return $action;
} } 下边新建 UserController.php <?php
namespace backend\controllers;
use Yii;
use yii\filters\auth\CompositeAuth;
use yii\filters\auth\QueryParamAuth;
use yii\data\ActiveDataProvider;
use \yii\helpers\Json;
use common\models\LoginForm; class UserController extends BaseActiveController
{
/**
* 判断用户登录信息,并返回结果。
* @author <sang.jiyu>
*/
public function actionIndex()
{
if(Yii::$app->user->isGuest){
$data=array(
'code'=>100,
'message'=>'用户未登录',
'data'=>'',
);
}else{
$data=array(
'code'=>200,
'message'=>'用户已经登录',
'data'=>array(
'user_id'=>Yii::$app->user->id,
'user_name'=>isset(\Yii::$app->user->identity->username) ? \Yii::$app->user->identity->username : '',
),
);
}
echo json_encode($data);exit;
} } 目录common/models下新建 User.php <?php
namespace common\models; use Yii;
use yii\base\NotSupportedException;
use yii\behaviors\TimestampBehavior;
use yii\db\ActiveRecord;
use yii\web\IdentityInterface; /**
* User model
*
* @property integer $id
* @property string $username
* @property string $password_hash
* @property string $password_reset_token
* @property string $email
* @property string $auth_key
* @property integer $status
* @property integer $created_at
* @property integer $updated_at
* @property integer $curr_login_ip
* @property integer $curr_login_at
* @property string $password write-only password
*/ class User extends ActiveRecord implements IdentityInterface
{ public $curr_login_at;
const STATUS_DELETED = 0;
const STATUS_ACTIVE = 10; /**
* @inheritdoc
*/
public static function tableName()
{
return '{{%user}}';
} /**
* @inheritdoc
*/
public function behaviors()
{
return [
TimestampBehavior::className(),
];
} # 生成access_token
public function generateAccessToken()
{
$this->access_token = Yii::$app->security->generateRandomString();
} /**
* @inheritdoc
*/
public function rules()
{
return [
['status', 'default', 'value' => self::STATUS_ACTIVE],
['status', 'in', 'range' => [self::STATUS_ACTIVE, self::STATUS_DELETED]],
];
} /**
* @inheritdoc
*/
public static function findIdentity($id)
{
return static::findOne(['id' => $id, 'status' => self::STATUS_ACTIVE]);
} public static function findIdentityByAccessToken($token, $type = null)
{ return static::findOne(['access_token' => $token]);
} /**
* Finds user by username
*
* @param string $username
* @return static|null
*/
public static function findByUsername($username)
{
return static::findOne(['username' => $username, 'status' => self::STATUS_ACTIVE]);
} /**
* Finds user by password reset token
*
* @param string $token password reset token
* @return static|null
*/
public static function findByPasswordResetToken($token)
{
if (!static::isPasswordResetTokenValid($token)) {
return null;
} return static::findOne([
'password_reset_token' => $token,
'status' => self::STATUS_ACTIVE,
]);
} /**
* Finds out if password reset token is valid
*
* @param string $token password reset token
* @return bool
*/
public static function isPasswordResetTokenValid($token)
{
if (empty($token)) {
return false;
} $timestamp = (int) substr($token, strrpos($token, '_') + 1);
$expire = Yii::$app->params['user.passwordResetTokenExpire'];
return $timestamp + $expire >= time();
} /**
* @inheritdoc
*/
public function getId()
{
return $this->getPrimaryKey();
} /**
* @inheritdoc
*/
public function getAuthKey()
{
return $this->auth_key;
} /**
* @inheritdoc
*/
public function validateAuthKey($authKey)
{
return $this->getAuthKey() === $authKey;
} /**
* Validates password
*
* @param string $password password to validate
* @return bool if password provided is valid for current user
*/
public function validatePassword($password)
{ return Yii::$app->security->validatePassword($password, $this->password_hash);
} /**
* Generates password hash from password and sets it to the model
*
* @param string $password
*/
public function setPassword($password)
{
$this->password_hash = Yii::$app->security->generatePasswordHash($password);
} /**
* Generates "remember me" authentication key
*/
public function generateAuthKey()
{
$this->auth_key = Yii::$app->security->generateRandomString();
} /**
* Generates new password reset token
*/
public function generatePasswordResetToken()
{
$this->password_reset_token = Yii::$app->security->generateRandomString() . '_' . time();
} /**
* Removes password reset token
*/
public function removePasswordResetToken()
{
$this->password_reset_token = null;
}
} 在新建LoginForm.php <?php
namespace common\models; use Yii;
use yii\base\Model; /**
* Login form
*/
class LoginForm extends Model
{
public $username;
public $password;
public $rememberMe = true; private $_user; /**
* @inheritdoc
*/
public function rules()
{
return [
// username and password are both required
[['username', 'password'], 'required'],
// rememberMe must be a boolean value
['rememberMe', 'boolean'],
// password is validated by validatePassword()
['password', 'validatePassword'],
];
} /**
* Validates the password.
* This method serves as the inline validation for password.
*
* @param string $attribute the attribute currently being validated
* @param array $params the additional name-value pairs given in the rule
*/
public function validatePassword($attribute, $params)
{
if (!$this->hasErrors()) {
$user = $this->getUser();
if (!$user || !$user->validatePassword($this->password)) {
$this->addError($attribute, 'Incorrect username or password.');
}
}
} /**
* Logs in a user using the provided username and password.
*
* @return bool whether the user is logged in successfully
*/
public function login()
{
if ($this->validate()) {
return Yii::$app->user->login($this->getUser(), $this->rememberMe ? 3600 * 24 * 30 : 0);
} else {
return false;
}
} /**
* Finds user by username
*
* @return User|null
*/
protected function getUser()
{
if ($this->_user === null) {
$this->_user = User::findByUsername($this->username);
} return $this->_user;
}
} http://localhost/yii2/backend/web/index.php?r=user/index&access-token=rMwh_EnqAc0qEPTfzb66BlGtSqoF15sg
没有作美化,大家自己处理一下吧,注意这个rMwh_EnqAc0qEPTfzb66BlGtSqoF15sg内容为数据库里的access-token这个内容里的值
返回内容为 {"code":200,"message":"\u7528\u6237\u5df2\u7ecf\u767b\u5f55","data":{"user_id":"1","user_name":"terry"}} 返回这个内容就成功了 下边完成登陆用户名和密码验证生成access-token的内容
在controllers这个目录下新建SiteController.php <?php
/**
*
*登陆接口access-token验证类
* @author 爱博
* 1.0
*
*
*/ namespace backend\controllers; use Yii;
use backend\models\forms\LoginForm;
use common\lib\Helper;
use yii\base\Exception;
use yii\base\InvalidValueException;
use yii\base\UserException;
use yii\web\ErrorAction;
use yii\web\HttpException;
use yii\rest\Controller; class SiteController extends Controller
{ public $modelClass = 'common\models\user';
public function behaviors()
{
$behaviors = parent::behaviors();
// unset($behaviors['authenticator']);
return $behaviors;
} protected function verbs()
{
$verbs = parent::verbs();
// $verbs['index'] = ['POST'];
return $verbs;
} public function actionLogin()
{ $loginModel = new LoginForm();
$loginModel->load([$loginModel->formName() => yii::$app->request->get()]); if ($loginModel->validate()) {
$rs = $loginModel->login(); return Helper::format_data($rs);
} else {
return Helper::format_data($loginModel->getErrors(), HTTP_STATUS_401);
}
}
} 运行http://localhost/yii2/backend/web/index.php?r=site/login&password=rasmuslerdorf&username=terry Use of undefined constant HTTP_STATUS_200 - assumed 'HTTP_STATUS_200' 返回这个内容就成功了
数据库如下:
/*
Navicat MySQL Data Transfer
Source Server : localhost
Source Server Version : 50553
Source Host : localhost:3306
Source Database : oauth2
Target Server Type : MYSQL
Target Server Version : 50553
File Encoding : 65001
Date: 2017-01-16 13:57:48
*/
SET FOREIGN_KEY_CHECKS=0;
-- Table structure for mxq_guide
DROP TABLE IF EXISTS mxq_guide
;
CREATE TABLE mxq_guide
(id
int(11) NOT NULL,imgurl
varchar(255) DEFAULT NULL,status
smallint(2) DEFAULT NULL,flag
smallint(2) DEFAULT NULL,
PRIMARY KEY (id
)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
-- Records of mxq_guide
INSERT INTO mxq_guide
VALUES ('0', 'ddd', '1', '1111');
INSERT INTO mxq_guide
VALUES ('2', 'ssss', '1', '2222');
INSERT INTO mxq_guide
VALUES ('3', '555', '4', '444');
-- Table structure for user
DROP TABLE IF EXISTS user
;
CREATE TABLE user
(id
int(20) unsigned NOT NULL AUTO_INCREMENT,username
varchar(50) DEFAULT NULL COMMENT '用户名',password_hash
varchar(80) DEFAULT NULL COMMENT '密码',password_reset_token
varchar(60) DEFAULT NULL COMMENT '密码token',email
varchar(60) DEFAULT NULL COMMENT '邮箱',auth_key
varchar(60) DEFAULT NULL,status
int(5) DEFAULT NULL COMMENT '状态',created_at
int(18) DEFAULT NULL COMMENT '创建时间',updated_at
int(18) DEFAULT NULL COMMENT '更新时间',password
varchar(50) DEFAULT NULL COMMENT '密码',role
varchar(50) DEFAULT NULL COMMENT 'role',curr_login_at
varchar(50) DEFAULT NULL,curr_login_ip
varchar(50) DEFAULT NULL,access_token
varchar(60) DEFAULT NULL,login_count
varchar(50) DEFAULT NULL,allowance
int(20) NOT NULL,allowance_updated_at
int(20) NOT NULL,
PRIMARY KEY (id
),
UNIQUE KEY username
(username
),
UNIQUE KEY access_token
(access_token
)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;
-- Records of user
INSERT INTO user
VALUES ('1', 'terry',
'$2y$07$BCryptRequires22Chrcte/VlQH0piJtjXl.0t1XkA8pw9dMXTpOq', null,
'zqy234@126.com', 'pBJi3hyFsLsTuvUM9paFpWjYRatn3qwS', '10',
'1441763620', '1484546128', null, null, '1484235121', '::1',
'qvuhh01lt4Q4GZnnLI2gdL1HwYR0nLWN', '17', '0', '1447318986');
INSERT INTO user
VALUES ('2', 'terry1',
'$2y$07$BCryptRequires22Chrcte/VlQH0piJtjXl.0t1XkA8pw9dMXTpOq', null,
'zqy2341@126.com', 'wIvJk7dMm6PQ1dJFz8iUqJ1RfH6rsDTW', '10',
'1441763906', '1484235959', null, null, '1484235121', '::1',
'_ydI-L1lQQwKZzoOWzMOUjMZ-t1PcM4k', '2', '0', '0');
INSERT INTO user
VALUES ('3', 'zqy',
'$2y$07$BCryptRequires22Chrcte/VlQH0piJtjXl.0t1XkA8pw9dMXTpOq', null,
'zqy23114@126.com', 'K-76pcy7gxceemxRI2IeN5g1EhLMaCj8', '10',
'1442544183', '1442544183', null, 'moderator', null, null, null, null,
'0', '0');
INSERT INTO user
VALUES ('4', 'admin',
'$2y$07$BCryptRequires22Chrcte/VlQH0piJtjXl.0t1XkA8pw9dMXTpOq', null,
'zqy2342321@126.com', 'hZWOaamjHEsPtuJJVghFRdE2oTj7Qv8P', '10',
'1446524232', '1446524232', null, null, null, null, null, null, '0',
'0');
数据库
yii2 restful api --app接口编程的更多相关文章
-
yii2 restful api——app接口编程实例
<?php namespace common\components; use common\models\Cart; use common\models\User; use Yii; use y ...
-
Yii2 Restful Api 401
采用Yii2 Restful Api方式为APP提供数据,默认你已经做好了所有的编码和配置工作.采用Postman测试接口: 出现这个画面的一个可能原因是:access_token的写法有误,如果你使 ...
-
Yii2 restful api创建,认证授权以及速率控制
Yii2 restful api创建,认证授权以及速率控制 下面是对restful从创建到速率控制的一个详细流程介绍,里面的步骤以及截图尽可能详细,熟悉restful的盆友可能觉得过于繁琐,新手不妨耐 ...
-
yii2 RESTful API 405 Method Not Allowed
关于 Yii2 中 RESTful API 的开发,可以参考另一篇随笔 http://www.cnblogs.com/ganiks/p/yii2-restful-api-dev.html 测试的过程中 ...
-
Yii2 Restful api设计--App接口编程
Yii2框架写一套RESTful风格的API,对照魏曦教你学 一,入门 一.目录结构 实现一个简单地RESTful API只需用到三个文件.目录如下: frontend ├─ config │ └ m ...
-
Yii2 Restful API 原理分析
Yii2 有个很重要的特性是对 Restful API的默认支持, 通过短短的几个配置就可以实现简单的对现有Model的RESTful API 参考另一篇文章: http://www.cnblogs. ...
-
yii2 RESTful API Develop
参考文档:http://www.yiiframework.com/doc-2.0/guide-rest.html 以 DB 中的 news 表为例创建该资源的 RESTful API,最终的测试通过工 ...
-
yii2 RESTful api的详细使用
作者:白狼 出处:http://www.manks.top/yii2-restful-api.html 本文版权归作者,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则 ...
-
Restful API及接口安全
一.简介 REST(Representational State Transfer,具体状态转移),是一种基于HTTP协议.URI(统一资源定位符).JSON和XML这些现有协议与标准的,针对网络应用 ...
随机推荐
-
UVa #11582 Colossal Fibonacci Numbers!
巨大的斐波那契数 The i'th Fibonacci number f (i) is recursively defined in the following way: f (0) = 0 and ...
-
【C#】【Thread】SynchronizationContext线程间同步
SynchronizationContext在通讯中充当传输者的角色,实现功能就是一个线程和另外一个线程的通讯. 需要注意的是,不是每个线程都附加SynchronizationContext这个对象, ...
-
c++学习-数组
int a[10]; //是个元素,在windows下回报错,linux会输出一个随机数 int a[10]={1,2}; //初始化,其他的为0 数组越界: 为了调高效率, 编译器不会对数组越界做检 ...
-
[C++]iostream的几种输入形式
做ACM题的时候,发现cin并不能满足所有输入要求.比如说: 每行给出一款运动鞋信息,若该款写不打折,则先后给出每种运动鞋单价P,所购买的数量Q:若打折,则先后给出每种运动鞋单价P,所购买的数量Q,折 ...
- unity 脚本(自定义组件)的事件触发关系
-
Android installed app, never used, cannot receiver BroadcastReceiver
官方文档是这么写的:(http://developer.android.com/about/versions/android-3.1.html#launchcontrols) Launch contr ...
-
angular控制器常用的4种通信方式
首先概括一下angular控制器通信的4种方式: 作用域继承. 通过$scope广播事件. 事件发射器模块. 服务. 1.作用域的继承 子作用域可以访问声明在它们的祖先作用域中的变量和函数. < ...
-
http响应结构分析
HTTP响应由三个部分组成: 1.状态码(Status Code): 描述了响应的状态.可以用来检查是否成功的完成了请求.请求失败的情况下,状态码可用来找出失败的原因.如果Servlet没有返回状态码 ...
-
Android中EditText显示明文与密文的两种方式
版权声明:本文为HaiyuKing原创文章,转载请注明出处! 前言 记录输入框显示.隐藏密码的简单布局以及实现方式. 效果图 代码分析 方式一 /**方式一:*/ private void sh ...
-
Linux系统一些常用命令(持续增加)
这些命令什么的全是从网上找的,防止忘记,留下来备忘 1.linux服务器如何从另一台服务器拷东西:可以用scp命令scp user@remote.machine:/remote/path /local ...