ExtLoginController.class.php 9.9 KB

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