/**
  * @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;
 }
Ejemplo n.º 2
0
 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'];
     });
 }
Ejemplo n.º 3
0
 /**
  * @return array
  * @throws \League\OAuth2\Server\Exception\InvalidClientException
  * @throws \League\OAuth2\Server\Exception\InvalidRefreshException
  * @throws \League\OAuth2\Server\Exception\InvalidRequestException
  * @throws \League\OAuth2\Server\Exception\InvalidScopeException
  */
 public function completeFlow()
 {
     $response = parent::completeFlow();
     // update user oauth token in session
     Session::put('oauth', $response);
     return $response;
 }
Ejemplo n.º 4
0
 /**
  * handle
  */
 public function handle()
 {
     $clientRepository = new ClientRepository();
     $scopeRepository = new ScopeRepository();
     $accessTokenRepository = new AccessTokenRepository();
     $userRepository = new UserRepository();
     $refreshTokenRepository = new RefreshTokenRepository();
     $config = Yii::$container->get(ConfigInterface::class);
     $privateKey = $config->get('privateKeyPath');
     $publicKey = $config->get('publicKeyPath');
     $server = new AuthorizationServer($clientRepository, $accessTokenRepository, $scopeRepository, $privateKey, $publicKey);
     $refreshTokenTTL = $config->get('refreshTokenTTL', 'P1M');
     $accessTokenTTL = $config->get('accessTokenTTL', 'PT1H');
     $grant = new PasswordGrant($userRepository, $refreshTokenRepository);
     $grant->setRefreshTokenTTL(new \DateInterval($refreshTokenTTL));
     $server->enableGrantType($grant, new \DateInterval($accessTokenTTL));
     return $server;
 }
 /**
  * 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;
     });
 }
Ejemplo n.º 6
0
 /**
  * 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);
 }
Ejemplo n.º 7
0
 public function completeFlow()
 {
     // Get the required params
     $clientId = $this->server->getRequest()->request->get('client_id', $this->server->getRequest()->getUser());
     if (is_null($clientId)) {
         throw new Exception\InvalidRequestException('client_id');
     }
     $clientSecret = $this->server->getRequest()->request->get('client_secret', $this->server->getRequest()->getPassword());
     if (is_null($clientSecret)) {
         throw new Exception\InvalidRequestException('client_secret');
     }
     $clientClass = $this->clientClass;
     // Validate client ID and client secret
     $client = \CHMS\Common\Models\BaseClient::where(['id' => $clientId, 'secret' => $clientSecret, 'allow_password_auth' => 1])->first();
     if (empty($client)) {
         $this->server->getEventEmitter()->emit(new Event\ClientAuthenticationFailedEvent($this->server->getRequest()));
         throw new Exception\InvalidClientException();
     }
     return parent::completeFlow();
 }
Ejemplo n.º 8
0
    return $security;
}, true);
$di->setShared('authorizationServer', function () use($di) {
    $config = $di->getShared('config');
    $server = new AuthorizationServer(new ClientRepository(), new AccessTokenRepository(), new ScopeRepository(), 'file://' . __DIR__ . '/' . $config->oauth['private'], 'file://' . __DIR__ . '/' . $config->oauth['public']);
    $userRepository = new UserRepository();
    $refreshTokenRepository = new RefreshTokenRepository();
    $authCodeRepository = new AuthCodeRepository();
    $accessTokenLifetime = new \DateInterval($config->oauth['accessTokenLifetime']);
    $refreshTokenLifetime = new \DateInterval($config->oauth['refreshTokenLifetime']);
    $authorizationCodeLifetime = new \DateInterval($config->oauth['authorizationCodeLifetime']);
    /**
     * Using client_id & client_secret & username & password
     *
     */
    $passwordGrant = new PasswordGrant($userRepository, $refreshTokenRepository);
    $passwordGrant->setRefreshTokenTTL($refreshTokenLifetime);
    $server->enableGrantType($passwordGrant, $accessTokenLifetime);
    /**
     * Using client_id & client_secret
     */
    $clientCredentialsGrant = new ClientCredentialsGrant();
    $server->enableGrantType($clientCredentialsGrant, $accessTokenLifetime);
    /**
     * Using client_id & client_secret
     */
    $refreshTokenGrant = new RefreshTokenGrant($refreshTokenRepository);
    $refreshTokenGrant->setRefreshTokenTTL($refreshTokenLifetime);
    $server->enableGrantType($refreshTokenGrant, $accessTokenLifetime);
    /**
     * Using response_type=code & client_id & redirect_uri & state
Ejemplo n.º 9
0
 /**
  * enable PasswordGrant.
  *
  * @param $options
  *
  * @return PasswordGrant
  */
 public function enablePasswordGrant($options)
 {
     // Init our repositories
     $userRepository = new UserRepository();
     // instance of UserRepositoryInterface
     $refreshTokenRepository = new RefreshTokenRepository();
     // instance of RefreshTokenRepositoryInterface
     $grant = new PasswordGrant($userRepository, $refreshTokenRepository);
     $grant->setRefreshTokenTTL($this->getDateInterval($options['refresh_token_ttl']));
     // Enable the password grant on the server
     $this->authorizationServer->enableGrantType($grant, $this->getDateInterval($options['access_token_ttl']));
     return $grant;
 }
Ejemplo n.º 10
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;
     }
 }