Oauth2.0 oauth2-server-php的使用Demo,怎么连接redis/可实现thinkphp5/yii/Laravel中使用
单点登录SSO本片教程没有华丽的说辞,只有实实在在的代码:https://github.com/liaoshengping/oauth2-php如果你没有接触oauth2.0,先无脑用原生php的跑一边,方便理解 Oauth2.0开发准备: 下载之后先执行:composer update1.数据库导入2.在service.php 设置数据库信息3.notice:在host 设...
介绍
介绍3种PHP-oauth 2 的模式。
1单点登录SSO
本片教程没有华丽的说辞,只有实实在在的代码: https://github.com/liaoshengping/oauth2-php
如果你没有接触oauth2.0,先无脑用原生php的跑一边,方便理解 Oauth2.0
开发准备: 下载之后先执行:composer install
1.数据库导入
2.在service.php 设置数据库信息
3.notice:在host 设置 oauth2.com 指向本地
获取access_token http://oauth2.com/token.php
post参数:
client_id:testclient
client_secret:testpass
grant_type:client_credentials //授权模式
结果:
{
"access_token": "8f27b59bb071b296fc58b1679c22f6c40411b9e7",
"expires_in": 60,
"token_type": "Bearer",
"scope": "trut"
}
2授权登录
1.先跳转到一个授权页面,并告诉授权服务器,来授权的是谁,工作的是authorize.php;(这个过程就像qq授权)
http://oauth2.com/authorize.php?response_type=code&client_id=testtest&state=%E8%BF%99%E4%B8%AA%E6%98%AF%E4%BD%A0%E8%A6%81%E5%B8%A6%E7%9A%84%E5%8F%82%E6%95%B0
点击授权
得到一个code
2.用这个code 去换 access_token http://oauth2.com/token.php
post参数:
client_id:testclient
client_secret:testpass
grant_type:authorization_code //授权模式
code:刚刚获取的code
如果成功:
{
"access_token": "e07ff1efcf82d8351d4ea55b79d9d64a77239231",
"expires_in": 3600,
"token_type": "Bearer",
"scope": null,
"refresh_token": "e71c1b23f146f50cf1d3db721a64bf4efb845f2c"
}
3用户密码模式
如果你想用username 和password 登录
在server.php 中加入
在$server 下面添加
$grantType = new OAuth2\GrantType\UserCredentials($storage);
$server->addGrantType($grantType);
你就可以用postman验证帐号密码了。
这个时候你可能会产生疑问,为什么我已经有username和password 验证之后,为什么还需要clientid 和secret ?
因为这个服务是面对开发的。当然clientid 是php后台处理加上去的,不是让登录者登录的。
在数据库的oauth_users表中添加
username:liaosp
password:7c4a8d09ca3762af61e59520943dc26494f8941b
注意:这边的password 是sha1()加密的sha1(123456) = 7c4a8d09ca3762af61e59520943dc26494f8941b
用postman测试:
恭喜你,已经成功的掌握了基本的oauth2的功能了,其他的功能,慢慢探索吧。
在自己项目中使用(应该聪明的你,能够举一反三,在各种框架中使用)
composer require bshaffer/oauth2-server-php
如果用redis做储存
composer require predis/predis:dev-master
在server.php 中添加 同时把pdo 连接的注释掉
比如添加一个用户的时候,同时也要更新redis 中的数据。这么初始化一个clinetid 为testtest ,和pdo获取的一样
$predis = new \Predis\Client(['scheme' =>'tcp',' host' =>'localhost','port' =>6379]);
$storage = new OAuth2\Storage\Redis($predis);
$storage->setClientDetails('testtest', 'testpass', 'http://baidu.com/','client_credentials','trut');
更多推荐
所有评论(0)