ExtLoginController.class.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252
  1. <?php
  2. namespace Api\Controller;
  3. use Think\Controller;
  4. class ExtLoginController extends BaseController {
  5. // 根据用户名和LoginSecretKey登录
  6. public function bySecretKey(){
  7. $username = I("username") ;
  8. $key = I("key") ;
  9. $time = I("time") ;
  10. $token = I("token") ;
  11. $redirect = I("redirect") ;
  12. if($time < (time() - 60) ){
  13. $this->sendError(10101,"已过期");
  14. return ;
  15. }
  16. $login_secret_key = D("Options")->get("login_secret_key") ;
  17. $new_token = md5($username.$login_secret_key.$time);
  18. if($token != $new_token){
  19. $this->sendError(10101,"token不正确");
  20. return ;
  21. }
  22. $res = D("User")->where("( username='%s' ) ",array($username))->find();
  23. if(!$res){
  24. D("User")->register($username,md5("savsnyjh".time().rand()));
  25. $res = D("User")->where("( username='%s' ) ",array($username))->find();
  26. }
  27. if($res){
  28. // var_dump($res); return ;
  29. if($res['groupid'] == 1){
  30. $this->sendError(10101,"为了安全,禁止管理员通过这种方式登录");
  31. return ;
  32. }
  33. D("User")->setLastTime($res['uid']);
  34. unset($res['password']);
  35. session("login_user" , $res );
  36. $token = D("UserToken")->createToken($res['uid'],60*60*24*180);
  37. cookie('cookie_token',$token,array('expire'=>60*60*24*180,'httponly'=>'httponly'));//此处由服务端控制token是否过期,所以cookies过期时间设置多久都无所谓
  38. if($redirect){
  39. $redirect = urldecode($redirect) ;
  40. header("location:{$redirect}");
  41. }else{
  42. header("location:../web/#/item/index");
  43. }
  44. }
  45. }
  46. public function oauth2(){
  47. $this->checkComposerPHPVersion();
  48. $redirect = I("redirect") ;
  49. session('redirect',$redirect) ;
  50. $oauth2_open = D("Options")->get("oauth2_open" ) ;
  51. $oauth2_form = D("Options")->get("oauth2_form" ) ;
  52. $oauth2_form = json_decode($oauth2_form,1);
  53. if(!$oauth2_open){
  54. echo "尚未启用oauth2";
  55. return ;
  56. }
  57. $clientId = $oauth2_form['client_id'] ;
  58. $clientSecret = $oauth2_form['client_secret'] ;
  59. $redirectUri = $oauth2_form['redirectUri'];
  60. $urlAuthorize = $oauth2_form['protocol']."://".$oauth2_form['host'].$oauth2_form['authorize_path'] ;
  61. $urlAccessToken = $oauth2_form['protocol']."://".$oauth2_form['host'].$oauth2_form['token_path'] ;
  62. $urlResourceOwnerDetails = $oauth2_form['protocol']."://".$oauth2_form['host'].$oauth2_form['resource_path'] ;
  63. if(strstr($oauth2_form['userinfo_path'],"://")){
  64. $urlUserInfo = $oauth2_form['userinfo_path'] ;
  65. }else{
  66. $urlUserInfo = $oauth2_form['protocol']."://".$oauth2_form['host'].$oauth2_form['userinfo_path'] ;
  67. }
  68. $provider = new \League\OAuth2\Client\Provider\GenericProvider([
  69. 'clientId' => $clientId, // The client ID assigned to you by the provider
  70. 'clientSecret' => $clientSecret, // The client password assigned to you by the provider
  71. 'redirectUri' => $redirectUri ,
  72. 'urlAuthorize' => $urlAuthorize,
  73. 'urlAccessToken' => $urlAccessToken,
  74. 'urlResourceOwnerDetails' => $urlResourceOwnerDetails,
  75. ],[
  76. 'httpClient' => new \GuzzleHttp\Client(['verify' => false]),
  77. ]);
  78. // If we don't have an authorization code then get one
  79. if (!isset($_GET['code'])) {
  80. // Fetch the authorization URL from the provider; this returns the
  81. // urlAuthorize option and generates and applies any necessary parameters
  82. // (e.g. state).
  83. $authorizationUrl = $provider->getAuthorizationUrl();
  84. // Get the state generated for you and store it to the session.
  85. $_SESSION['oauth2state'] = $provider->getState();
  86. // Redirect the user to the authorization URL.
  87. header('Location: ' . $authorizationUrl);
  88. exit;
  89. // Check given state against previously stored one to mitigate CSRF attack
  90. } elseif (empty($_GET['state']) || (isset($_SESSION['oauth2state']) && $_GET['state'] !== $_SESSION['oauth2state'])) {
  91. if (isset($_SESSION['oauth2state'])) {
  92. unset($_SESSION['oauth2state']);
  93. }
  94. exit('Invalid state');
  95. } else {
  96. try {
  97. // Try to get an access token using the authorization code grant.
  98. $accessToken = $provider->getAccessToken('authorization_code', [
  99. 'code' => $_GET['code']
  100. ]);
  101. // We have an access token, which we may use in authenticated
  102. // requests against the service provider's API.
  103. //echo 'Access Token: ' . $accessToken->getToken() . "<br>";
  104. //echo 'Refresh Token: ' . $accessToken->getRefreshToken() . "<br>";
  105. //echo 'Expired in: ' . $accessToken->getExpires() . "<br>";
  106. // echo 'Already expired? ' . ($accessToken->hasExpired() ? 'expired' : 'not expired') . "<br>";
  107. $res = http_post($urlUserInfo,array(
  108. "access_token"=>$accessToken->getToken()
  109. ));
  110. $res_array = json_decode($res, true);
  111. if($res_array){
  112. $username = $res_array['username'] ;
  113. $info = D("User")->where("username='%s'" ,array($username))->find();
  114. if(!$info){
  115. D("User")->register($username,md5($username.time().rand()));
  116. $info = D("User")->where("username='%s'" ,array($username))->find();
  117. }
  118. D("User")->setLastTime($info['uid']);
  119. unset($info['password']);
  120. session("login_user" , $info );
  121. $token = D("UserToken")->createToken($info['uid'],60*60*24*180);
  122. cookie('cookie_token',$token,array('expire'=>60*60*24*180,'httponly'=>'httponly'));//此处由服务端控制token是否过期,所以cookies过期时间设置多久都无所谓
  123. if(session('redirect')){
  124. $redirect = urldecode(session('redirect')) ;
  125. header("location:{$redirect}");
  126. session('redirect',null) ;
  127. }else{
  128. header("location:../web/#/item/index");
  129. }
  130. }else{
  131. echo "登录成功但无法获取用户信息";
  132. }
  133. } catch (\League\OAuth2\Client\Provider\Exception\IdentityProviderException $e) {
  134. // Failed to get the access token or user details.
  135. exit($e->getMessage());
  136. }
  137. }
  138. }
  139. public function cas(){
  140. $this->checkComposerPHPVersion();
  141. define("CAS_VERSION_1_0", '1.0');
  142. define("CAS_VERSION_2_0", '2.0');
  143. define("CAS_VERSION_3_0", '3.0');
  144. # 2 开启phpCAS debug
  145. \phpCAS::setDebug();
  146. # 3 初始化phpCAS,参数说明:
  147. # a) CAS协议版本号
  148. # b) cas server的域名
  149. # c) cas server的端口号
  150. # d) cas server的项目访问路径
  151. \phpCAS::client(CAS_VERSION_2_0, '192.168.8.160', 8443, '/maxkey/authz/cas/');
  152. # 4 开启设置证书验证。如果是开发环境可将此注释,如果是生产环境为了安全性建议将此开启
  153. // phpCAS::setCasServerCACert($cas_server_ca_cert_path);
  154. # 5 不为CAS服务器设置SSL验证
  155. # 为了快速测试,您可以禁用CAS服务器的SSL验证。此建议不建议用于生产环境。验证CAS服务器对CAS协议的安全性至关重要!
  156. \phpCAS::setNoCasServerValidation();
  157. # 6 这里会检测服务器端的退出的通知,就能实现php和其他语言平台间同步登出了
  158. # 处理登出请求。cas服务端会发送请求通知客户端。如果没有同步登出,可能是服务端跟客户端无法通信(比如我的客户端是localhost, 服务端在云上)
  159. \phpCAS::handleLogoutRequests();
  160. # 7 进行CAS服务验证,这个方法确保用户是否验证过,如果没有验证则跳转到验证界面
  161. # 这个是强制认证模式,查看 CAS.php 可以找到几种不同的方式:
  162. # a) forceAuthentication - phpCAS::forceAuthentication();
  163. # b) checkAuthentication - phpCAS::checkAuthentication();
  164. # c) renewAuthentication - phpCAS::renewAuthentication();
  165. # 根据自己需要调用即可。
  166. $auth = \phpCAS::forceAuthentication();
  167. if ($auth) {
  168. var_dump($auth);
  169. return ;
  170. # 8 验证通过,或者说已经登陆系统,可进行已经登陆之后的逻辑处理...
  171. # 获得登陆CAS用户的名称
  172. $user_name = \phpCAS::getUser();
  173. echo $user_name . '已经成功登陆...<br>';
  174. # 9 你还可打印保存的phpCAS session信息
  175. print_r($_SESSION);
  176. # 10 还可获取有关已验证用户的属性,例如:$uid = phpCAS::getAttribute('id');
  177. $attr = \phpCAS::getAttributes();
  178. print_r($attr);
  179. # 11 进行退出的相关操作
  180. # 在你的PHP项目中处理完相应的退出逻辑之后,还需执行phpCAS::logout()进行CAS系统的退出
  181. # 当我们访问cas服务端的logout的时候,cas服务器会发送post请求到各个已经登录的客户端
  182. //phpCAS::logout();
  183. # 登出方法一:登出成功后跳转的地址
  184. //phpCAS::setServerLoginUrl("https://192.168.1.120:80/cas/logout?embed=true&service=http://localhost/phpCasClient/user.php?a=login");
  185. //phpCAS::logout();
  186. # 登出方法二:退出登录后返回地址
  187. //$param = array("service" => "http://cas.x.com");
  188. //phpCAS::logout($param);
  189. } else {
  190. # 12 验证未通过,说明未进行登陆
  191. # 将会跳转回你配置的CAS SSO SERVER服务的域名;
  192. # 在你输入正确的用户名和密码之后CAS会自动跳转回service=http%3A%2F%2Fcas.x.com%2F此地址
  193. # 在此你可以处理验证未通过的各种逻辑
  194. echo '还未登陆,跳转到CAS进行登陆...<br>';
  195. }
  196. }
  197. }