/**
  * @return array
  * @throws InvalidRequestException
  * @throws InvalidCredentialsException
  * @throws InvalidClientException
  * @throws ServerException
  * @throws \League\OAuth2\Server\Exception\UnsupportedGrantTypeException
  */
 public function actionLogin()
 {
     $user = null;
     $passwordGrant = new PasswordGrant();
     $modelClass = $this->modelClass;
     $user = $modelClass::findOne(['username' => Yii::$app->request->post("username"), 'status' => $modelClass::STATUS_ACTIVE]);
     $passwordGrant->setVerifyCredentialsCallback(function ($username, $password) {
         /* @var $modelClass User */
         $modelClass = $this->modelClass;
         /* @var $user User */
         $user = $modelClass::findOne(['username' => $username, 'status' => $modelClass::STATUS_ACTIVE]);
         if ($user !== null && $user->validatePassword($password)) {
             return $user->getId();
         } else {
             return false;
         }
     });
     $this->server->addGrantType($passwordGrant);
     try {
         $response = $this->server->issueAccessToken("password");
     } catch (InvalidCredentialsException $e) {
         throw new InvalidCredentialsException(Yii::t("rowasc.oauth", $e->getMessage()));
     } catch (InvalidClientException $e) {
         throw new InvalidClientException(Yii::t("rowasc.oauth", $e->getMessage()));
     } catch (InvalidRequestException $e) {
         throw new InvalidRequestException(Yii::t("rowasc.oauth", $e->getMessage()));
     } catch (UnsupportedGrantTypeException $e) {
         throw new OAuthException(Yii::t("rowasc.oauth", $e->getMessage()));
     }
     if (isset($response["access_token"])) {
         $response["user_id"] = $user->getId();
     }
     return $response;
 }
 public function register(Application $app)
 {
     parent::register($app);
     $app[AuthorizationServer::class] = $app->share(function () use($app) {
         /** @var AuthorizationServer $server */
         $server = (new AuthorizationServer())->setAccessTokenStorage($app['oauth.accesstoken-storage'])->setSessionStorage($app['oauth.session-storage'])->setRefreshTokenStorage($app['oauth.refreshtoken-storage'])->setClientStorage($app['oauth.client-storage'])->setScopeStorage($app['oauth.scope-storage'])->setAuthCodeStorage($app['oauth.authcode-storage']);
         // standard auth code grant
         $authCodeGrant = new AuthCodeGrant();
         $server->addGrantType($authCodeGrant);
         // password grant used by our apps
         $passwordGrant = new PasswordGrant();
         $passwordGrant->setVerifyCredentialsCallback(function ($username, $password) use($app) {
             /** @var OAuth2AuthenticatorInterface $auth */
             $auth = $app['oauth.authenticator'];
             $user = $auth->findUser(['username' => $username]);
             if ($user) {
                 return $auth->authenticate($user, ['username' => $username, 'password' => $password]);
             }
             return false;
         });
         $server->addGrantType($passwordGrant);
         $refreshTokenGrant = new RefreshTokenGrant();
         $refreshTokenGrant->setRequireClientSecret(false);
         $server->addGrantType($refreshTokenGrant);
         return $server;
     });
     $app[ResourceServer::class] = $app->share(function () use($app) {
         return new ResourceServer($app['oauth.session-storage'], $app['oauth.accesstoken-storage'], $app['oauth.client-storage'], $app['oauth.scope-storage']);
     });
     $app['security.authentication_listener.factory.oauth'] = $app->protect(function ($name) use($app) {
         $app['security.authentication_provider.' . $name . '.oauth'] = $app->share(function ($app) {
             return $app[OAuth2Provider::class];
         });
         $app['security.authentication_listener.' . $name . '.oauth'] = $app->share(function ($app) {
             return $app[OAuth2Listener::class];
         });
         return ['security.authentication_provider.' . $name . '.oauth', 'security.authentication_listener.' . $name . '.oauth', null, 'pre_auth'];
     });
     $app['security.authentication_listener.factory.oauth-optional'] = $app->protect(function ($name) use($app) {
         $app['security.authentication_provider.' . $name . '.oauth-optional'] = $app->share(function ($app) {
             $provider = new OAuth2Provider();
             $provider->setContainer($app);
             return $provider;
         });
         $app['security.authentication_listener.' . $name . '.oauth-optional'] = $app->share(function ($app) {
             $provider = new OAuth2OptionalListener();
             $provider->setContainer($app);
             return $provider;
         });
         return ['security.authentication_provider.' . $name . '.oauth-optional', 'security.authentication_listener.' . $name . '.oauth-optional', null, 'pre_auth'];
     });
 }
 /**
  * Register the Authorisation Server
  *
  * @return void
  */
 private function authorisation()
 {
     $this->app->singleton('League\\OAuth2\\Server\\AuthorizationServer', function ($app) {
         $server = new AuthorizationServer();
         $server->setSessionStorage(new SessionStorage($app->make('db')));
         $server->setAccessTokenStorage(new AccessTokenStorage($app->make('db')));
         $server->setRefreshTokenStorage(new RefreshTokenStorage($app->make('db')));
         $server->setClientStorage(new ClientStorage($app->make('db')));
         $server->setScopeStorage(new ScopeStorage($app->make('db')));
         $server->setAuthCodeStorage(new AuthCodeStorage($app->make('db')));
         $passwordGrant = new PasswordGrant();
         $passwordGrant->setVerifyCredentialsCallback(function ($user, $pass) {
             return true;
         });
         $server->addGrantType($passwordGrant);
         $refreshTokenGrant = new RefreshTokenGrant();
         $server->addGrantType($refreshTokenGrant);
         $server->setRequest($app['request']);
         return $server;
     });
 }
 /**
  * This extended constructor is setting up
  * the underlying AuthorizationServer with
  * the grant types that GLPi Plugins support
  * on it's OAuth2 Framework
  */
 public function __construct()
 {
     parent::__construct();
     $this->setSessionStorage(OAuthHelper::getSessionStorage());
     $this->setAccessTokenStorage(OAuthHelper::getAccessTokenStorage());
     $this->setRefreshTokenStorage(OAuthHelper::getRefreshTokenStorage());
     $this->setClientStorage(OAuthHelper::getClientStorage());
     $this->setScopeStorage(OAuthHelper::getScopeStorage());
     $this->setAuthCodeStorage(new AuthCodeStorage());
     // Adding the password grant to able users to login by themselves
     $passwordGrant = new PasswordGrant();
     $passwordGrant->setVerifyCredentialsCallback(function ($login, $password) {
         $user = User::where(function ($q) use($login) {
             return $q->where('email', '=', $login)->orWhere('username', '=', $login);
         });
         $count = $user->count();
         if ($count < 1) {
             return false;
         }
         if ($count > 1) {
             throw new \Exception('Dangerous, query result count > 1 when user tried' . ' to log with login "' . $login . '" ' . 'and password "' . $password . '"');
             return false;
         } elseif ($count == 0) {
             return false;
         } else {
             $user = $user->first();
             if ($user->assertPasswordIs($password)) {
                 return $user->id;
             } else {
                 return false;
             }
         }
     });
     $this->addGrantType($passwordGrant);
     $appGrant = new ClientCredentialsGrant();
     $this->addGrantType($appGrant);
     $refreshTokenGrant = new RefreshTokenGrant();
     $this->addGrantType($refreshTokenGrant);
 }
Exemple #5
0
 public function POST()
 {
     if (!isset($this->config['oauth'][$_SERVER['__version']])) {
         throw new \Exception('Forbidden.', 403);
     } elseif (!isset($_REQUEST['grant_type'])) {
         throw new \Exception('Bad Request.', 400);
     }
     $config = $this->config['oauth'][$_SERVER['__version']];
     switch (substr($_REQUEST['request'], strlen($_SERVER['__version']) + 2)) {
         case 'oauth/access_token':
             try {
                 $server = new AuthorizationServer();
                 $server->setSessionStorage(new SessionStorage());
                 $server->setAccessTokenStorage(new AccessTokenStorage());
                 $server->setClientStorage(new ClientStorage());
                 $server->setScopeStorage(new ScopeStorage());
                 $server->setRefreshTokenStorage(new RefreshTokenStorage());
                 $grant_type = $_REQUEST['grant_type'];
                 $grants = ['password'];
                 if (isset($config['grants'])) {
                     $grants = array_unique(array_merge($grants, $config['grants']));
                 }
                 if (!in_array($grant_type, $grants)) {
                     throw new \Exception('Unsupported grant type.', 403);
                 }
                 // Defaults TTLs to 1 day and 1 week respectively
                 $token_ttl = 3600;
                 $refresh_ttl = 604800;
                 if (isset($config['ttl']['access_token'])) {
                     $token_ttl = $config['ttl']['access_token'];
                 }
                 switch ($grant_type) {
                     case 'authorization_code':
                         throw new \Exception('Not Implemented', 501);
                         break;
                     case 'client_credentials':
                         throw new \Exception('Not Implemented', 501);
                         break;
                     case 'implicit':
                         throw new \Exception('Not Implemented', 501);
                         break;
                     case 'password':
                         $grant = new PasswordGrant();
                         $grant->setAccessTokenTTL($token_ttl);
                         $grant->setVerifyCredentialsCallback(function ($username, $password) {
                             $user = new User(['conditions' => ['email' => $username]]);
                             return $user->count() && password_verify($password, $user->record['password']);
                         });
                         break;
                     case 'refresh_token':
                         throw new \Exception('Not Implemented', 501);
                         // @todo Need to work through this, appears lib is busted
                         $grant = new RefreshTokenGrant();
                         //$grant->setAccessTokenTTL($refresh_ttl);
                         $server->addGrantType($grant);
                         break;
                 }
                 $server->addGrantType($grant);
                 // Adds the refresh token grant if enabled
                 if ($grant_type != 'refresh_token' && in_array('refresh_token', $grants)) {
                     if (isset($config['ttl']['refresh_token'])) {
                         $refresh_ttl = $config['ttl']['refresh_token'];
                     }
                     $grant = new RefreshTokenGrant();
                     $grant->setAccessTokenTTL($refresh_ttl);
                     $server->addGrantType($grant);
                 }
                 $response = $server->issueAccessToken();
                 return $response;
             } catch (OAuthException $e) {
                 throw new \Exception($e->getMessage(), $e->httpStatusCode);
             } catch (\Exception $e) {
                 throw new \Exception($e->getMessage(), $e->getCode());
             }
             break;
         default:
             throw new \Exception('Not Found.', 404);
             break;
     }
 }