Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 0 additions & 3 deletions module/VuFind/config/module.config.php
Original file line number Diff line number Diff line change
Expand Up @@ -179,7 +179,6 @@
'VuFind\Controller\LibGuidesAZController' => 'VuFind\Controller\AbstractBaseFactory',
'VuFind\Controller\LibraryCardsController' => 'VuFind\Controller\AbstractBaseFactory',
'VuFind\Controller\MyResearchController' => 'VuFind\Controller\MyResearchControllerFactory',
'VuFind\Controller\OAuth2Controller' => 'VuFind\Controller\OAuth2ControllerFactory',
'VuFind\Controller\OverdriveController' => 'VuFind\Controller\AbstractBaseFactory',
'VuFind\Controller\Pazpar2Controller' => 'VuFind\Controller\AbstractBaseFactory',
'VuFind\Controller\PrimoController' => 'VuFind\Controller\AbstractBaseFactory',
Expand Down Expand Up @@ -227,8 +226,6 @@
'librarycards' => 'VuFind\Controller\LibraryCardsController',
'MyResearch' => 'VuFind\Controller\MyResearchController',
'myresearch' => 'VuFind\Controller\MyResearchController',
'OAuth2' => 'VuFind\Controller\OAuth2Controller',
'oauth2' => 'VuFind\Controller\OAuth2Controller',
'Overdrive' => 'VuFind\Controller\OverdriveController',
'overdrive' => 'VuFind\Controller\OverdriveController',
'Pazpar2' => 'VuFind\Controller\Pazpar2Controller',
Expand Down
119 changes: 119 additions & 0 deletions module/VuFind/src/VuFind/Action/OAuth2/AbstractOAuth2Action.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
<?php

/**
* Abstract base class for OAuth2 actions.
*
* PHP version 8
*
* Copyright (C) The National Library of Finland 2022-2026.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, see
* <https://www.gnu.org/licenses/>.
*
* @category VuFind
* @package Action
* @author Ere Maijala <ere.maijala@helsinki.fi>
* @license http://opensource.org/licenses/gpl-2.0.php GNU General Public License
* @link https://vufind.org Main Site
*/

namespace VuFind\Action\OAuth2;

use Laminas\Http\Response;
use League\OAuth2\Server\Exception\OAuthServerException;
use Psr\Http\Message\ResponseInterface;
use VuFind\Action\AbstractTemplateRenderingAction;
use VuFind\ActionHelper\ResponseHelper;
use VuFind\OAuth2\OAuth2ServerService;
use VuFind\ServiceManager\Factory\Autowire;

/**
* Abstract base class for OAuth2 actions.
*
* @category VuFind
* @package Action
* @author Ere Maijala <ere.maijala@helsinki.fi>
* @license http://opensource.org/licenses/gpl-2.0.php GNU General Public License
* @link https://vufind.org Main Site
*/
abstract class AbstractOAuth2Action extends AbstractTemplateRenderingAction
{
/**
* Constructor.
*
* @param OAuth2ServerService $oauth2Service OAuth2 server service
*/
#[Autowire]
public function __construct(
protected OAuth2ServerService $oauth2Service,
) {
parent::__construct();
}

/**
* Create a server error response.
*
* @param ResponseInterface $response Response
* @param string $function Function description
* @param \Exception $e Exception
*
* @return ResponseInterface
*/
protected function handleOAuth2ServerException(
ResponseInterface $response,
string $function,
\Exception $e
): ResponseInterface {
$this->logError("$function failed: " . (string)$e);

return $this->convertOAuthServerExceptionToResponse(
$response,
OAuthServerException::serverError('Server side issue')
);
}

/**
* Create a server error response from a returnable exception.
*
* @param ResponseInterface $response Response
* @param string $function Function description
* @param \Exception $e Exception
*
* @return ResponseInterface
*/
protected function handleOAuth2Exception(
ResponseInterface $response,
string $function,
\Exception $e

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

convertOAuthServerExceptionToResponse assumes that $e will have a generateHttpResponse method, which I assume is not part of the base exception class. Do we need a more specific type here, or some kind of type checking later?

): ResponseInterface {
$this->logError("$function exception: " . (string)$e);

return $this->convertOAuthServerExceptionToResponse($response, $e);
}

/**
* Convert an instance of OAuthServerException to a response.
*
* @param ResponseInterface $response Response
* @param OAuthServerException $exception Exception
*
* @return ResponseInterface
*/
protected function convertOAuthServerExceptionToResponse(
ResponseInterface $response,
OAuthServerException $exception
): ResponseInterface {
$response = $exception->generateHttpResponse($response);
return $this->getHelper(ResponseHelper::class)->addCorsHeaders($response);
}
}
169 changes: 169 additions & 0 deletions module/VuFind/src/VuFind/Action/OAuth2/AuthorizeAction.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,169 @@
<?php

/**
* OAuth2 authorization action.
*
* PHP version 8
*
* Copyright (C) The National Library of Finland 2022-2026.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, see
* <https://www.gnu.org/licenses/>.
*
* @category VuFind
* @package Action
* @author Ere Maijala <ere.maijala@helsinki.fi>
* @license http://opensource.org/licenses/gpl-2.0.php GNU General Public License
* @link https://vufind.org Main Site
*/

namespace VuFind\Action\OAuth2;

use Exception;
use League\OAuth2\Server\Exception\OAuthServerException;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use VuFind\ActionHelper\FormHelper;
use VuFind\ActionHelper\LoginHelper;
use VuFind\Auth\Manager as AuthManager;
use VuFind\Db\Service\AccessTokenServiceInterface;
use VuFind\Db\Service\PluginManager as DbServicePluginManager;
use VuFind\Exception\BadRequest as BadRequestException;
use VuFind\ILS\Connection;
use VuFind\OAuth2\Entity\ScopeEntity;
use VuFind\OAuth2\OAuth2ServerService;
use VuFind\ServiceManager\Factory\Autowire;
use VuFind\Validator\CsrfInterface;

use function in_array;

/**
* OAuth2 authorization action.
*
* @category VuFind
* @package Action
* @author Ere Maijala <ere.maijala@helsinki.fi>
* @license http://opensource.org/licenses/gpl-2.0.php GNU General Public License
* @link https://vufind.org Main Site
*/
class AuthorizeAction extends AbstractOAuth2Action
{
/**
* Constructor.
*
* @param OAuth2ServerService $oauth2Service OAuth2 server service
* @param AuthManager $authManager Authentication manager
* @param CsrfInterface $csrf CSRF validator
* @param AccessTokenServiceInterface $accessTokenService Access token database service
* @param Connection $ilsConnection ILS connection
*/
public function __construct(
OAuth2ServerService $oauth2Service,
protected AuthManager $authManager,
protected CsrfInterface $csrf,
#[Autowire(container: DbServicePluginManager::class)]
protected AccessTokenServiceInterface $accessTokenService,
protected Connection $ilsConnection
) {
parent::__construct($oauth2Service);
}

/**
* Handle an authorization request.
*
* @param ServerRequestInterface $request Server request
* @param ResponseInterface $response Response
*
* @return ResponseInterface
*/
public function action(

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It would be nice to move more of the logic in this method to OAuth2ServerService, but it's not easy because it's a multi-step operation with different outcomes depending e.g. on the user login status.

ServerRequestInterface $request,
ResponseInterface $response,
): ResponseInterface {
// Validate the authorization request:
$clientId = $this->getQueryParam('client_id', '');
if (
'' === $clientId
|| !($clientConfig = $this->oauth2Service->getClientConfig($clientId))
) {
throw new BadRequestException("Invalid OAuth2 client $clientId");
}

if (!($user = $this->authManager->getUserObject())) {
return $this->getHelper(LoginHelper::class)
->forceLogin($request, $response, 'external_auth_access_login_message');
}

$authServer = $this->oauth2Service->getAuthorizationServer($clientId);
try {
$authRequest = $authServer->validateAuthorizationRequest($request);
} catch (OAuthServerException $e) {
return $this->handleOAuth2Exception($response, 'Authorization request', $e);
} catch (\Exception $e) {
return $this->handleOAuth2ServerException($response, 'Authorization request', $e);
}

// Hide any scopes not allowed by a client-specific filter (see also ScopeRepository for the actual filtering):
if ($allowedScopes = $clientConfig['allowedScopes'] ?? null) {
$scopes = $authRequest->getScopes();
array_map(
function ($scope) use ($allowedScopes): void {
if (!in_array($scope->getIdentifier(), $allowedScopes)) {
if (!($scope instanceof ScopeEntity)) {
throw new Exception('Scope must be an instance of ScopeEntity');
}
$scope->setHidden(true);
}
},
$scopes
);
$authRequest->setScopes($scopes);
}

$formHelper = $this->getHelper(FormHelper::class);
if ($formHelper->formWasSubmitted($request, ['allow', 'deny'])) {
// Check CSRF and session:
if (!$this->csrf->isValid($this->getPostParam('csrf'))) {
throw new \VuFind\Exception\BadRequest('error_inconsistent_parameters');
}

// Store OpenID nonce (or null if not present to clear any existing one)
// in the access token table so that it can be retrieved for token or
// user info action:
Comment on lines +140 to +142

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

With the new line length, this looks a little unbalanced; might as well rewrap:

Suggested change
// Store OpenID nonce (or null if not present to clear any existing one)
// in the access token table so that it can be retrieved for token or
// user info action:
// Store OpenID nonce (or null if not present to clear any existing one) in the access
// token table so that it can be retrieved for token or user info action:

$this->accessTokenService->storeNonce($user->getId(), $this->getQueryParam('nonce'));

$authRequest->setUser($this->oauth2Service->getOAuth2UserEntity($user));
$authRequest->setAuthorizationApproved($formHelper->formWasSubmitted($request, 'allow'));

try {
return $authServer->completeAuthorizationRequest($authRequest, $response);
} catch (OAuthServerException $e) {
return $this->handleOAuth2Exception($response, 'Authorization request', $e);
} catch (\Exception $e) {
return $this->handleOAuth2ServerException($response, 'Authorization request', $e);
}
}

$userIdentifierField = $this->oauth2Service->getUserIdentifierField();
$patron = $this->getHelper(LoginHelper::class)->catalogLogin($request, $response, false);
if ($patron instanceof ResponseInterface) {
return $patron;
}
$showCatalogLoginForm = !$patron;
return $this->renderTemplate(
$request,
$response,
compact('authRequest', 'user', 'patron', 'showCatalogLoginForm', 'userIdentifierField')
);
}
}
68 changes: 68 additions & 0 deletions module/VuFind/src/VuFind/Action/OAuth2/JwksAction.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
<?php

/**
* OAuth2 JWKS action.
*
* PHP version 8
*
* Copyright (C) The National Library of Finland 2022-2026.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, see
* <https://www.gnu.org/licenses/>.
*
* @category VuFind
* @package Action
* @author Ere Maijala <ere.maijala@helsinki.fi>
* @license http://opensource.org/licenses/gpl-2.0.php GNU General Public License
* @link https://vufind.org Main Site
*/

namespace VuFind\Action\OAuth2;

use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use VuFind\ActionHelper\ResponseHelper;

/**
* OAuth2 JWKS action.
*
* @category VuFind
* @package Action
* @author Ere Maijala <ere.maijala@helsinki.fi>
* @license http://opensource.org/licenses/gpl-2.0.php GNU General Public License
* @link https://vufind.org Main Site
*/
class JwksAction extends AbstractOAuth2Action
{
/**
* Handle a token request.
*
* @param ServerRequestInterface $request Server request
* @param ResponseInterface $response Response
*
* @return ResponseInterface
*/
public function action(
ServerRequestInterface $request,
ResponseInterface $response,
): ResponseInterface {
// Check that authorization server can be created (means that config is good):
if (!$this->oauth2Service->configValid()) {
return $this->renderNotFoundPage($request, $response);
}

$responseHelper = $this->getHelper(ResponseHelper::class);
$response = $responseHelper->getJsonResponse($response, $this->oauth2Service->getJwks());
return $responseHelper->addCorsHeaders($response);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Another where the original code does not seem to include CORS. Probably not a problem, just an observation.

}
}
Loading