ExtLoginController.class.php 3.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. <?php
  2. namespace Api\Controller;
  3. use Think\Controller;
  4. class ExtLoginController extends BaseController {
  5. public function oauth2(){
  6. $provider = new \League\OAuth2\Client\Provider\GenericProvider([
  7. 'clientId' => 'a36df4c9-5ed4-440b-8f69-7535d2947213', // The client ID assigned to you by the provider
  8. 'clientSecret' => 'F2m6MjIwNTIwMjEyMjE3NDYxMTM8Lr', // The client password assigned to you by the provider
  9. 'redirectUri' => 'http://192.168.8.160:8280/showdoc/server/?s=/api/ExtLogin/oauth2',
  10. 'urlAuthorize' => 'https://192.168.8.160:8443/maxkey/authz/oauth/v20/authorize',
  11. 'urlAccessToken' => 'https://192.168.8.160:8443/maxkey/authz/oauth/v20/token',
  12. 'urlResourceOwnerDetails' => 'https://192.168.8.160:8443/maxkey/authz/oauth/v20/resource',
  13. ],[
  14. 'httpClient' => new \GuzzleHttp\Client(['verify' => false]),
  15. ]);
  16. // If we don't have an authorization code then get one
  17. if (!isset($_GET['code'])) {
  18. // Fetch the authorization URL from the provider; this returns the
  19. // urlAuthorize option and generates and applies any necessary parameters
  20. // (e.g. state).
  21. $authorizationUrl = $provider->getAuthorizationUrl();
  22. // Get the state generated for you and store it to the session.
  23. $_SESSION['oauth2state'] = $provider->getState();
  24. // Redirect the user to the authorization URL.
  25. header('Location: ' . $authorizationUrl);
  26. exit;
  27. // Check given state against previously stored one to mitigate CSRF attack
  28. } elseif (empty($_GET['state']) || (isset($_SESSION['oauth2state']) && $_GET['state'] !== $_SESSION['oauth2state'])) {
  29. if (isset($_SESSION['oauth2state'])) {
  30. unset($_SESSION['oauth2state']);
  31. }
  32. exit('Invalid state');
  33. } else {
  34. try {
  35. // Try to get an access token using the authorization code grant.
  36. $accessToken = $provider->getAccessToken('authorization_code', [
  37. 'code' => $_GET['code']
  38. ]);
  39. // We have an access token, which we may use in authenticated
  40. // requests against the service provider's API.
  41. echo 'Access Token: ' . $accessToken->getToken() . "<br>";
  42. echo 'Refresh Token: ' . $accessToken->getRefreshToken() . "<br>";
  43. echo 'Expired in: ' . $accessToken->getExpires() . "<br>";
  44. echo 'Already expired? ' . ($accessToken->hasExpired() ? 'expired' : 'not expired') . "<br>";
  45. $res = http_post('https://192.168.8.160:8443/maxkey/api/oauth/v20/me',array(
  46. "access_token"=>$accessToken->getToken()
  47. ));
  48. var_dump($res);
  49. } catch (\League\OAuth2\Client\Provider\Exception\IdentityProviderException $e) {
  50. // Failed to get the access token or user details.
  51. exit($e->getMessage());
  52. }
  53. }
  54. }
  55. }