yii2 提供接口给java_Yii 2 RESTful API使用OAuth2进行身份验证(Yii 2高级模板)

REST API无需身份验证方法即可运行 . 现在,我想通过移动应用程序对API请求的OAuth2身份验证验证REST API . 我试过yii2指南,但它对我不起作用 .

基本上移动用户需要使用用户名和密码登录,如果用户名和密码正确,则用户需要登录,并且需要使用令牌进一步验证API请求 .

用户表中的access_token字段为空 . 我需要手动保存吗?如何将access_token作为响应返回?

用户是否有任何理由同时使用这三种方法(HttpBasicAuth,HttpBearerAuth,QueryParamAuth),为什么?怎么样?

我的应用程序文件夹结构如下所示 .

api

-config

-modules

--v1

---controllers

---models

-runtime

-tests

-web

backend

common

console

environments

frontend

API \模块\ V1 \ Module.php

namespace api\modules\v1;

class Module extends \yii\base\Module

{

public $controllerNamespace = 'api\modules\v1\controllers';

public function init()

{

parent::init();

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

}

}

API \模块\ V1 \控制器\ CountryController.php

namespace api\modules\v1\controllers;

use Yii;

use yii\rest\ActiveController;

use common\models\LoginForm;

use common\models\User;

use yii\filters\auth\CompositeAuth;

use yii\filters\auth\HttpBasicAuth;

use yii\filters\auth\HttpBearerAuth;

use yii\filters\auth\QueryParamAuth;

/**

* Country Controller API

*

* @author Budi Irawan

*/

class CountryController extends ActiveController

{

public $modelClass = 'api\modules\v1\models\Country';

public function behaviors()

{

$behaviors = parent::behaviors();

$behaviors['authenticator'] = [

//'class' => HttpBasicAuth::className(),

'class' => CompositeAuth::className(),

'authMethods' => [

HttpBasicAuth::className(),

HttpBearerAuth::className(),

QueryParamAuth::className(),

],

];

return $behaviors;

}

}

常见\型号\ user.php的

namespace common\models;

use Yii;

use yii\base\NotSupportedException;

use yii\behaviors\TimestampBehavior;

use yii\db\ActiveRecord;

use yii\web\IdentityInterface;

class User extends ActiveRecord implements IdentityInterface

{

const STATUS_DELETED = 0;

const STATUS_ACTIVE = 10;

public static function tableName()

{

return '{{%user}}';

}

public function behaviors()

{

return [

TimestampBehavior::className(),

];

}

public function rules()

{

return [

['status', 'default', 'value' => self::STATUS_ACTIVE],

['status', 'in', 'range' => [self::STATUS_ACTIVE, self::STATUS_DELETED]],

];

}

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]);

}

}

用户表

id

username

auth_key

password_hash

password_reset_token

email

status

created_at

access_token

迁移用户表后添加了access_token

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值