请大神指导一下 yii2.0 的 oauth2 什么玩

Yii2中OAuth扩展及QQ互联登录实现方法,yii2oauth
原创
 08:39:38
772
Yii2中OAuth扩展及QQ互联登录实现方法,yii2oauth本文实例讲述了Yii2中OAuth扩展及QQ互联登录实现方法。分享给大家供大家参考,具体如下:
复制代码 代码如下:php composer.phar require --prefer-dist yiisoft/yii2-authclient "*"
Quick start 快速开始
更改Yii2的配置文件config/main.php,在components中增加如下内容
'components' =& [
'authClientCollection' =& [
'class' =& 'yii\authclient\Collection',
'clients' =& [
'google' =& [
'class' =& 'yii\authclient\clients\GoogleOpenId'
'facebook' =& [
'class' =& 'yii\authclient\clients\Facebook',
'clientId' =& 'facebook_client_id',
'clientSecret' =& 'facebook_client_secret',
更改入口文件,一般是app/controllers/SiteController.php,在function actions增加代码,同时增加回调函数successCallback,大致如下
class SiteController extends Controller
public function actions()
'auth' =& [
'class' =& 'yii\authclient\AuthAction',
'successCallback' =& [$this, 'successCallback'],
public function successCallback($client)
$attributes = $client-&getUserAttributes();
// user login or signup comes here
在登录的Views中,增加如下代码
&?= yii\authclient\widgets\AuthChoice::widget([
'baseAuthUrl' =& ['site/auth']
以上是官方的说明文档,下面我们来接入QQ互联
增加QQ登录的组件 我这里是放在 common/components/QqOAuth.php 中,源代码如下
namespace common\
use yii\authclient\OAuth2;
use yii\base\E
use yii\helpers\J
* 'components' =& [
* 'authClientCollection' =& [
'class' =& 'yii\authclient\Collection',
'clients' =& [
'class' =& 'common\components\QqOAuth',
'clientId' =& 'qq_client_id',
'clientSecret' =& 'qq_client_secret',
* @see http://connect.qq.com/
* @author easypao &&
* @since 2.0
class QqOAuth extends OAuth2
public $authUrl = 'https://graph.qq.com/oauth2.0/authorize';
public $tokenUrl = 'https://graph.qq.com/oauth2.0/token';
public $apiBaseUrl = 'https://graph.qq.com';
public function init()
parent::init();
if ($this-&scope === null) {
$this-&scope = implode(',', [
'get_user_info',
protected function initUserAttributes()
$openid = $this-&api('oauth2.0/me', 'GET');
$qquser = $this-&api("user/get_user_info", 'GET', ['oauth_consumer_key'=&$openid['client_id'], 'openid'=&$openid['openid']]);
$qquser['openid']=$openid['openid'];
protected function defaultName()
return 'qq';
protected function defaultTitle()
return 'Qq';
* 该扩展初始的处理方法似乎QQ互联不能用,应此改写了方法
* @see \yii\authclient\BaseOAuth::processResponse()
protected function processResponse($rawResponse, $contentType = self::CONTENT_TYPE_AUTO)
if (empty($rawResponse)) {
return [];
switch ($contentType) {
case self::CONTENT_TYPE_AUTO: {
$contentType = $this-&determineContentTypeByRaw($rawResponse);
if ($contentType == self::CONTENT_TYPE_AUTO) {
//以下代码是特别针对QQ互联登录的,也是与原方法不一样的地方
if(strpos($rawResponse, "callback") !== false){
$lpos = strpos($rawResponse, "(");
$rpos = strrpos($rawResponse, ")");
$rawResponse = substr($rawResponse, $lpos + 1, $rpos - $lpos -1);
$response = $this-&processResponse($rawResponse, self::CONTENT_TYPE_JSON);
//代码添加结束
throw new Exception('Unable to determine response content type automatically.');
$response = $this-&processResponse($rawResponse, $contentType);
case self::CONTENT_TYPE_JSON: {
$response = Json::decode($rawResponse, true);
if (isset($response['error'])) {
throw new Exception('Response error: ' . $response['error']);
case self::CONTENT_TYPE_URLENCODED: {
$response = [];
parse_str($rawResponse, $response);
case self::CONTENT_TYPE_XML: {
$response = $this-&convertXmlToArray($rawResponse);
default: {
throw new Exception('Unknown response type "' . $contentType . '".');
更改 config/main.php 文件,在components中增加,大致如下
'components' =& [
'authClientCollection' =& [
'class' =& 'yii\authclient\Collection',
'clients' =& [
'class'=&'common\components\QqOAuth',
'clientId'=&'your_qq_clientid',
'clientSecret'=&'your_qq_secret'
SiteController.php 就按官方那样子
public function successCallback($client)
$attributes = $client-&getUserAttributes();
// 用户的信息在$attributes中,以下是您根据您的实际情况增加的代码
// 如果您同时有QQ互联登录,新浪微博等,可以通过 $client-&id 来区别。
最后在登录的视图文件中 增加QQ登录链接
&a href="/site/auth?authclient=qq"&使用QQ快速登录&/a&
PS:小编在这里推荐一款本站的php格式化美化的排版工具帮助大家在以后的PHP程序设计中进行代码排版:
php代码在线格式化美化工具:http://tools.jb51.net/code/phpformat
更多关于Yii相关内容感兴趣的读者可查看本站专题:《Yii框架入门及常用技巧总结》、《php优秀开发框架总结》、《smarty模板入门基础教程》、《php日期与时间用法总结》、《php面向对象程序设计入门教程》、《php字符串(string)用法总结》、《php+mysql数据库操作入门教程》及《php常见数据库操作技巧汇总》
希望本文所述对大家基于Yii框架的PHP程序设计有所帮助。
江湖传言:PHP是世界上最好的编程语言。真的是这样吗?这个梗究竟是从哪来的?学会本课程,你就会明白了。
PHP中文网出品的PHP入门系统教学视频,完全从初学者的角度出发,绝不玩虚的,一切以实用、有用...
ThinkPHP是国内最流行的中文PHP开发框架,也是您Web项目的最佳选择。《php.cn独孤九贱(5)-ThinkPHP5视频教程》课程以ThinkPHP5最新版本为例,从最基本的框架常识开始,将...
《php.cn原创html5视频教程》课程特色:php中文网原创幽默段子系列课程,以恶搞,段子为主题风格的php视频教程!轻松的教学风格,简短的教学模式,让同学们在不知不觉中,学会了HTML知识。
本套教程,以一个真实的学校教学管理系统为案例,手把手教会您如何在一张白纸上,从零开始,一步一步的用ThinkPHP5框架快速开发出一个商业项目。
所有计算机语言的学习都要从基础开始,《PHP入门视频教程之一周学会PHP》不仅是PHP的基础部分更主要的是PHP语言的核心技术,是学习PHP必须掌握的内容,任何PHP项目的实现都离不开这部分的内容,通...
本课以最新版ThinkPHP5.0.10为基础进行开发,全程实录一个完整企业点,从后台到前台,从控制器到路由的全套完整教程,不论是你是新人,还是有一定开发经验的程序员,都可以从中学到实用的知识~~
ThinkPHP是一个快速、开源的轻量级国产PHP开发框架,是业内最流行的PHP框架之一。本课程以博客系统为例,讲述如何使用TP实战开发,从中学习Thinkphp的实践应用。模版下载地址:http:/...
本课程是php实战开发课程,以爱奇艺电影网站为蓝本从零开发一个自己的网站。目的是让大家了解真实项目的架构及开发过程
本课以一个极简的PHP开发框架为案例,向您展示了一个PHP框架应该具有的基本功能,以及具体的实现方法,让您快速对PHP开发框架的底层实现有一个清楚的认识,为以后学习其实的开发框架打下坚实的基础。
javascript是运行在浏览器上的脚本语言,连续多年,被评为全球最受欢迎的编程语言。是前端开发必备三大法器中,最具杀伤力。如果前端开发是降龙十八掌,好么javascript就是第18掌:亢龙有悔。...
本站9月直播课已经结束,本套教程是直播实录,没有报上名或者漏听学员福利来了,赶紧看看吧,说不定这里就有你的菜
轻松明快,简洁生动,让你快速走入HTML5的世界,体会语义化开发的魅力
JavaScript能够称得上是史上使用最广泛的编程语言,也是前端开发必须掌握的三技能之一:描述网页内容的HTML、描述网页样式的CSS以及描述网页行为的JavaScript。本章节将帮助大家迅速掌握...
Bootstrap 是最受欢迎的 HTML、CSS 和 JS 框架,用于开发响应式布局、移动设备优先的 WEB 项目。为所有开发者、所有应用场景而设计,它让前端开发更快速、简单,所有开发者都能快速上手...
《php.cn独孤九贱(2)-css视频教程》课程特色:php中文网原创幽默段子系列课程,以恶搞,段子为主题风格的php视频教程!轻松的教学风格,简短的教学模式,让同学们在不知不觉中,学会了CSS知识...
《php用户注册登录系统》主要介绍网站的登录注册功能,我们会从最简单的实现登录注册功能开始,增加验证码,cookie验证等,丰富网站的登录注册功能
jQuery是一个快速、简洁的JavaScript框架。设计的宗旨是“write Less,Do More”,即倡导写更少的代码,做更多的事情。它封装JavaScript常用的功能代码,提供一种简便的...
《PHP学生管理系统视频教程》主要给大家讲解了HTML,PHP,MySQL之间的相互协作,实现动态的网页显示和获取数据.
《最新微信小程序开发视频教程》本节课程是由微趋道录制,讲述了如何申请一个微信小程序,以及开发中需要使用哪些工具,和需要注意哪些等。
《弹指间学会HTML视频教程》从最基本的概念开始讲起,步步深入,带领大家学习HTML,了解各种常用标签的意义以及基本用法,学习HTML知识为以后的学习打下基础
全栈工程师
文章总浏览数filsh/yii2-oauth2-server - Packagist
OAuth2 Server for PHP
Type:yii2-extension
Requires (Dev)
e05fffcf0eae276ea36e9e87ae3e2
Igor Maliy
A wrapper for implementing an OAuth2 Server()
Installation
The preferred way to install this extension is through .
Either run
php composer.phar require --prefer-dist filsh/yii2-oauth2-server "*"
"filsh/yii2-oauth2-server": "~2.0"
to the require section of your composer.json.
To use this extension,
simply add the following code in your application configuration as a new module:
'modules'=&[
//other modules .....
'oauth2' =& [
'class' =& 'filsh\yii2\oauth2server\Module',
'tokenParamName' =& 'accessToken',
'tokenAccessLifetime' =& 3600 * 24,
'storageMap' =& [
'user_credentials' =& 'app\models\User',
'grantTypes' =& [
'user_credentials' =& [
'class' =& 'OAuth2\GrantType\UserCredentials',
'refresh_token' =& [
'class' =& 'OAuth2\GrantType\RefreshToken',
'always_issue_new_refresh_token' =& true
If you want to get Json Web Token (JWT) instead of convetional token, you will need to set 'useJwtToken' =& true in module and then define two more configurations:
'public_key' =& 'app\storage\PublicKeyStorage' which is the class that implements
and 'access_token' =& 'app\storage\JwtAccessToken' which implements
For Oauth2 base library provides the default
which works great except that it tries to save the token in the database. So I decided to inherit from it and override the part that tries to save (token size is too big and crashes with VARCHAR(40) in the database.
TL;DR, here are the sample classes
access_token
namespace app\storage;
* @author Stefano Mtangoo &mwinjilisti at gmail dot com&
class JwtAccessToken extends \OAuth2\Storage\JwtAccessToken
public function setAccessToken($oauth_token, $client_id, $user_id, $expires, $scope = null)
public function unsetAccessToken($access_token)
and public_key
namespace app\storage;
class PublicKeyStorage implements \OAuth2\Storage\PublicKeyInterface{
private $pbk =
private $pvk =
public function __construct()
//files should be in same directory as this file
//keys can be generated using OpenSSL tool with command:
private key:
openssl genrsa -out privkey.pem 2048
public key:
openssl rsa -in privkey.pem -pubout -out pubkey.pem
$this-&pbk =
file_get_contents('privkey.pem', true);
$this-&pvk =
file_get_contents('pubkey.pem', true);
public function getPublicKey($client_id = null){
$this-&pbk;
public function getPrivateKey($client_id = null){
$this-&pvk;
public function getEncryptionAlgorithm($client_id = null){
return 'HS256';
NOTE: You will need
PR applied or you can patch it yourself by checking changes in . The other part of PR is only if you want to use firebase JWT library (which is not mandatory anyway).
Also, extend common\models\User - user model - implementing the interface \OAuth2\Storage\UserCredentialsInterface, so the oauth2 credentials data stored in user table.
You should implement:
findIdentityByAccessToken()
checkUserCredentials()
getUserDetails()
You can extend the model if you prefer it (please, remember to update the config files) :
class User extends common\models\User implements \OAuth2\Storage\UserCredentialsInterface
* Implemented for Oauth2 Interface
public static function findIdentityByAccessToken($token, $type = null)
/** @var \filsh\yii2\oauth2server\Module $module */
$module = Yii::$app-&getModule('oauth2');
$token = $module-&getServer()-&getResourceController()-&getToken();
return !empty($token['user_id'])
? static::findIdentity($token['user_id'])
* Implemented for Oauth2 Interface
public function checkUserCredentials($username, $password)
$user = static::findByUsername($username);
if (empty($user)) {
return $user-&validatePassword($password);
* Implemented for Oauth2 Interface
public function getUserDetails($username)
$user = static::findByUsername($username);
return ['user_id' =& $user-&getId()];
The next step your shold run migration
yii migrate --migrationPath=@vendor/filsh/yii2-oauth2-server/migrations
this migration create the oauth2 database scheme and insert test user credentials testclient:testpass for http://fake/
add url rule to urlManager
'urlManager' =& [
'enablePrettyUrl' =& true, //only if you want to use petty URLs
'rules' =& [
'POST oauth2/&action:\w+&' =& 'oauth2/rest/&action&',
To use this extension,
simply add the behaviors for your base controller:
use yii\helpers\ArrayHelper;
use yii\filters\auth\HttpBearerAuth;
use yii\filters\auth\QueryParamAuth;
use filsh\yii2\oauth2server\filters\ErrorToExceptionFilter;
use filsh\yii2\oauth2server\filters\auth\CompositeAuth;
class Controller extends \yii\rest\Controller
* @inheritdoc
public function behaviors()
return ArrayHelper::merge(parent::behaviors(), [
'authenticator' =& [
'class' =& CompositeAuth::className(),
'authMethods' =& [
['class' =& HttpBearerAuth::className()],
['class' =& QueryParamAuth::className(), 'tokenParam' =& 'accessToken'],
'exceptionFilter' =& [
'class' =& ErrorToExceptionFilter::className()
To get access token (js example):
var url = window.location.host + "/oauth2/token";
var data = {
'grant_type':'password',
'username':'&some login from your user table&',
'password':'&real pass&',
'client_id':'testclient',
'client_secret':'testpass'
//ajax POST `data` to `url` here
For more, see使用 OAuth2-Server-php 在 Yii 框架上搭建 OAuth2 Server_百度文库
您的浏览器Javascript被禁用,需开启后体验完整功能,
享专业文档下载特权
&赠共享文档下载特权
&100W篇文档免费专享
&每天抽奖多种福利
两大类热门资源免费畅读
续费一年阅读会员,立省24元!
使用 OAuth2-Server-php 在 Yii 框架上搭建 OAuth2 Server
心宽体胖科技运营总监|
总评分0.0|
用知识赚钱
阅读已结束,下载本文需要
定制HR最喜欢的简历
下载文档到电脑,同时保存到云知识,更方便管理
加入VIP
还剩10页未读,
定制HR最喜欢的简历
你可能喜欢

我要回帖

更多关于 yii 的文章

 

随机推荐