'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', ] ], ] ], // ...... ],
use yii\filters\auth\QueryParamAuth;
public function behaviors()
{
return ArrayHelper::merge (parent::behaviors(), [
'authenticator' => [
'class' => QueryParamAuth::className()
]
] );
}
public function behaviors()
{
return ArrayHelper::merge (parent::behaviors(), [
'authenticator' => [
'class' => QueryParamAuth::className(),
'optional' => [
'login',
'signup-test'
],
]
] );
}
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
];
}
/**
* 登录
*/
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;
}
}
<?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 = 'generate_api_token';
public function init ()
{
parent::init();
$this->on(self::GET_API_TOKEN, [$this, 'onGenerateApiToken']);
}
/**
* @inheritdoc
* 对客户端表单数据进行验证的rule
*/
public function rules()
{
return [
[['username', 'password'], 'required'],
['password', 'validatePassword'],
];
}
/**
* 自定义的密码认证方法
*/
public function validatePassword($attribute, $params)
{
if (!$this->hasErrors()) {
$this->_user = $this->getUser();
if (!$this->_user || !$this->_user->validatePassword($this->password)) {
$this->addError($attribute, '用户名或密码错误.');
}
}
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'username' => '用户名',
'password' => '密码',
];
}
/**
* 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);
}
}
}
/**
* 生成 api_token
*/
public function generateApiToken()
{
$this->api_token = Yii::$app->security->generateRandomString() . '_' . time();
}
/**
* 校验api_token是否有效
*/
public static function apiTokenIsValid($token)
{
if (empty($token)) {
return false;
}
$timestamp = (int) substr($token, strrpos($token, '_') + 1);
$expire = Yii::$app->params['user.apiTokenExpire'];
return $timestamp + $expire >= time();
}
<?php return [ // ... // token 有效期默认1天 'user.apiTokenExpire' => 1*24*3600, ];
public function behaviors()
{
return ArrayHelper::merge (parent::behaviors(), [
'authenticator' => [
'class' => QueryParamAuth::className(),
'tokenParam' => 'token',
'optional' => [
'login',
'signup-test'
],
]
] );
}
'extraPatterns' => [ 'POST login' => 'login', 'GET signup-test' => 'signup-test', 'GET user-profile' => 'user-profile', ]
public static function findIdentityByAccessToken($token, $type = null)
{
// 如果token无效的话,
if(!static::apiTokenIsValid($token)) {
throw new \yii\web\UnauthorizedHttpException("token is invalid.");
}
return static::findOne(['api_token' => $token, 'status' => self::STATUS_ACTIVE]);
// throw new NotSupportedException('"findIdentityByAccessToken" is not implemented.');
}
/**
* 获取用户信息
*/
public function actionUserProfile ($token)
{
// 到这一步,token都认为是有效的了
// 下面只需要实现业务逻辑即可,下面仅仅作为案例,比如你可能需要关联其他表获取用户信息等等
$user = User::findIdentityByAccessToken($token);
return [
'id' => $user->id,
'username' => $user->username,
'email' => $user->email,
];
}
'response' => [
'class' => 'yii\web\Response',
'on beforeSend' => function ($event) {
$response = $event->sender;
$response->format = yii\web\Response::FORMAT_JSON;
},
],
yii\web\BadRequestHttpException yii\web\ForbiddenHttpException yii\web\NotFoundHttpException yii\web\ServerErrorHttpException yii\web\UnauthorizedHttpException yii\web\TooManyRequestsHttpException
'response' => [
'class' => 'yii\web\Response',
'on beforeSend' => function ($event) {
$response = $event->sender;
$response->data = [
'code' => $response->getStatusCode(),
'data' => $response->data,
'message' => $response->statusText
];
$response->format = yii\web\Response::FORMAT_JSON;
},
],
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有