2020-07-01 17:27:50 -04:00
|
|
|
<?php namespace BookStack\Auth\Access;
|
|
|
|
|
|
|
|
use BookStack\Auth\User;
|
|
|
|
use BookStack\Exceptions\JsonDebugException;
|
|
|
|
use BookStack\Exceptions\OpenIdException;
|
|
|
|
use BookStack\Exceptions\UserRegistrationException;
|
|
|
|
use Exception;
|
2021-10-06 12:12:01 -04:00
|
|
|
use Lcobucci\JWT\Signer\Rsa\Sha256;
|
2020-07-01 17:27:50 -04:00
|
|
|
use Lcobucci\JWT\Token;
|
2020-07-06 20:26:00 -04:00
|
|
|
use League\OAuth2\Client\Provider\Exception\IdentityProviderException;
|
2020-07-01 17:27:50 -04:00
|
|
|
use OpenIDConnectClient\AccessToken;
|
2021-10-06 12:12:01 -04:00
|
|
|
use OpenIDConnectClient\Exception\InvalidTokenException;
|
2020-07-01 17:27:50 -04:00
|
|
|
use OpenIDConnectClient\OpenIDConnectProvider;
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Class OpenIdService
|
|
|
|
* Handles any app-specific OpenId tasks.
|
|
|
|
*/
|
|
|
|
class OpenIdService extends ExternalAuthService
|
|
|
|
{
|
|
|
|
protected $config;
|
|
|
|
|
|
|
|
/**
|
|
|
|
* OpenIdService constructor.
|
|
|
|
*/
|
|
|
|
public function __construct(RegistrationService $registrationService, User $user)
|
|
|
|
{
|
2020-07-06 12:14:43 -04:00
|
|
|
parent::__construct($registrationService, $user);
|
|
|
|
|
2021-10-06 12:12:01 -04:00
|
|
|
$this->config = config('oidc');
|
2020-07-01 17:27:50 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
2021-10-06 12:12:01 -04:00
|
|
|
* Initiate an authorization flow.
|
|
|
|
* @throws Exception
|
2020-07-01 17:27:50 -04:00
|
|
|
*/
|
|
|
|
public function login(): array
|
|
|
|
{
|
|
|
|
$provider = $this->getProvider();
|
|
|
|
return [
|
|
|
|
'url' => $provider->getAuthorizationUrl(),
|
|
|
|
'state' => $provider->getState(),
|
|
|
|
];
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Initiate a logout flow.
|
|
|
|
*/
|
|
|
|
public function logout(): array
|
|
|
|
{
|
|
|
|
$this->actionLogout();
|
|
|
|
$url = '/';
|
|
|
|
$id = null;
|
|
|
|
|
|
|
|
return ['url' => $url, 'id' => $id];
|
|
|
|
}
|
|
|
|
|
2020-07-06 20:26:00 -04:00
|
|
|
/**
|
|
|
|
* Refresh the currently logged in user.
|
2021-10-06 12:12:01 -04:00
|
|
|
* @throws Exception
|
2020-07-06 20:26:00 -04:00
|
|
|
*/
|
|
|
|
public function refresh(): bool
|
|
|
|
{
|
|
|
|
// Retrieve access token for current session
|
|
|
|
$json = session()->get('openid_token');
|
2020-08-04 15:29:11 -04:00
|
|
|
|
|
|
|
// If no access token was found, reject the refresh
|
|
|
|
if (!$json) {
|
|
|
|
$this->actionLogout();
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
2020-07-09 12:29:44 -04:00
|
|
|
$accessToken = new AccessToken(json_decode($json, true) ?? []);
|
2020-07-06 20:26:00 -04:00
|
|
|
|
2020-08-04 16:09:53 -04:00
|
|
|
// If the token is not expired, refreshing isn't necessary
|
|
|
|
if ($this->isUnexpired($accessToken)) {
|
2020-07-06 20:26:00 -04:00
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
2020-08-04 16:09:53 -04:00
|
|
|
// Try to obtain refreshed access token
|
|
|
|
try {
|
|
|
|
$newAccessToken = $this->refreshAccessToken($accessToken);
|
2021-10-06 12:12:01 -04:00
|
|
|
} catch (Exception $e) {
|
2020-08-04 16:09:53 -04:00
|
|
|
// Log out if an unknown problem arises
|
|
|
|
$this->actionLogout();
|
|
|
|
throw $e;
|
|
|
|
}
|
|
|
|
|
|
|
|
// If a token was obtained, update the access token, otherwise log out
|
|
|
|
if ($newAccessToken !== null) {
|
|
|
|
session()->put('openid_token', json_encode($newAccessToken));
|
|
|
|
return true;
|
|
|
|
} else {
|
2020-07-06 20:26:00 -04:00
|
|
|
$this->actionLogout();
|
|
|
|
return false;
|
|
|
|
}
|
2020-08-04 16:09:53 -04:00
|
|
|
}
|
|
|
|
|
2020-08-04 18:18:43 -04:00
|
|
|
/**
|
|
|
|
* Check whether an access token or OpenID token isn't expired.
|
|
|
|
*/
|
2020-08-04 16:09:53 -04:00
|
|
|
protected function isUnexpired(AccessToken $accessToken): bool
|
|
|
|
{
|
|
|
|
$idToken = $accessToken->getIdToken();
|
|
|
|
|
|
|
|
$accessTokenUnexpired = $accessToken->getExpires() && !$accessToken->hasExpired();
|
|
|
|
$idTokenUnexpired = !$idToken || !$idToken->isExpired();
|
|
|
|
|
|
|
|
return $accessTokenUnexpired && $idTokenUnexpired;
|
|
|
|
}
|
|
|
|
|
2020-08-04 18:18:43 -04:00
|
|
|
/**
|
|
|
|
* Generate an updated access token, through the associated refresh token.
|
2021-10-06 12:12:01 -04:00
|
|
|
* @throws Exception
|
2020-08-04 18:18:43 -04:00
|
|
|
*/
|
2020-08-04 16:09:53 -04:00
|
|
|
protected function refreshAccessToken(AccessToken $accessToken): ?AccessToken
|
|
|
|
{
|
|
|
|
// If no refresh token available, abort
|
|
|
|
if ($accessToken->getRefreshToken() === null) {
|
|
|
|
return null;
|
|
|
|
}
|
2020-07-06 20:26:00 -04:00
|
|
|
|
|
|
|
// ID token or access token is expired, we refresh it using the refresh token
|
|
|
|
try {
|
2020-08-04 16:09:53 -04:00
|
|
|
return $this->getProvider()->getAccessToken('refresh_token', [
|
2020-07-06 20:26:00 -04:00
|
|
|
'refresh_token' => $accessToken->getRefreshToken(),
|
|
|
|
]);
|
|
|
|
} catch (IdentityProviderException $e) {
|
2020-08-04 16:09:53 -04:00
|
|
|
// Refreshing failed
|
|
|
|
return null;
|
2020-07-06 20:26:00 -04:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-07-01 17:27:50 -04:00
|
|
|
/**
|
|
|
|
* Process the Authorization response from the authorization server and
|
|
|
|
* return the matching, or new if registration active, user matched to
|
|
|
|
* the authorization server.
|
|
|
|
* Returns null if not authenticated.
|
2021-10-06 12:12:01 -04:00
|
|
|
* @throws Exception
|
|
|
|
* @throws InvalidTokenException
|
2020-07-01 17:27:50 -04:00
|
|
|
*/
|
|
|
|
public function processAuthorizeResponse(?string $authorizationCode): ?User
|
|
|
|
{
|
|
|
|
$provider = $this->getProvider();
|
|
|
|
|
|
|
|
// Try to exchange authorization code for access token
|
|
|
|
$accessToken = $provider->getAccessToken('authorization_code', [
|
|
|
|
'code' => $authorizationCode,
|
|
|
|
]);
|
|
|
|
|
|
|
|
return $this->processAccessTokenCallback($accessToken);
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Do the required actions to log a user out.
|
|
|
|
*/
|
|
|
|
protected function actionLogout()
|
|
|
|
{
|
|
|
|
auth()->logout();
|
|
|
|
session()->invalidate();
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
2020-07-06 20:26:00 -04:00
|
|
|
* Load the underlying OpenID Connect Provider.
|
2020-07-01 17:27:50 -04:00
|
|
|
*/
|
|
|
|
protected function getProvider(): OpenIDConnectProvider
|
|
|
|
{
|
2020-07-09 10:27:45 -04:00
|
|
|
// Setup settings
|
2021-10-06 12:12:01 -04:00
|
|
|
$settings = [
|
|
|
|
'clientId' => $this->config['client_id'],
|
|
|
|
'clientSecret' => $this->config['client_secret'],
|
|
|
|
'idTokenIssuer' => $this->config['issuer'],
|
|
|
|
'redirectUri' => url('/openid/redirect'),
|
|
|
|
'urlAuthorize' => $this->config['authorization_endpoint'],
|
|
|
|
'urlAccessToken' => $this->config['token_endpoint'],
|
|
|
|
'urlResourceOwnerDetails' => null,
|
|
|
|
'publicKey' => $this->config['jwt_public_key'],
|
|
|
|
'scopes' => 'profile email',
|
|
|
|
];
|
2020-07-01 17:27:50 -04:00
|
|
|
|
2020-07-09 10:27:45 -04:00
|
|
|
// Setup services
|
2021-10-06 12:12:01 -04:00
|
|
|
$services = [
|
|
|
|
'signer' => new Sha256(),
|
2020-07-09 10:27:45 -04:00
|
|
|
];
|
2020-07-01 17:27:50 -04:00
|
|
|
|
2021-10-06 12:12:01 -04:00
|
|
|
return new OpenIDConnectProvider($settings, $services);
|
2020-07-01 17:27:50 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Calculate the display name
|
|
|
|
*/
|
|
|
|
protected function getUserDisplayName(Token $token, string $defaultValue): string
|
|
|
|
{
|
2021-10-06 12:12:01 -04:00
|
|
|
$displayNameAttr = $this->config['display_name_claims'];
|
2020-07-01 17:27:50 -04:00
|
|
|
|
|
|
|
$displayName = [];
|
|
|
|
foreach ($displayNameAttr as $dnAttr) {
|
2021-10-06 12:12:01 -04:00
|
|
|
$dnComponent = $token->claims()->get($dnAttr, '');
|
2020-07-01 17:27:50 -04:00
|
|
|
if ($dnComponent !== '') {
|
|
|
|
$displayName[] = $dnComponent;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if (count($displayName) == 0) {
|
2021-10-06 12:12:01 -04:00
|
|
|
$displayName[] = $defaultValue;
|
2020-07-01 17:27:50 -04:00
|
|
|
}
|
|
|
|
|
2021-10-06 12:12:01 -04:00
|
|
|
return implode(' ', $displayName);;
|
2020-07-01 17:27:50 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
2020-07-06 20:26:00 -04:00
|
|
|
* Extract the details of a user from an ID token.
|
2020-07-01 17:27:50 -04:00
|
|
|
*/
|
|
|
|
protected function getUserDetails(Token $token): array
|
|
|
|
{
|
2021-10-06 12:12:01 -04:00
|
|
|
$id = $token->claims()->get('sub');
|
2020-07-01 17:27:50 -04:00
|
|
|
return [
|
2021-10-06 12:12:01 -04:00
|
|
|
'external_id' => $id,
|
|
|
|
'email' => $token->claims()->get('email'),
|
|
|
|
'name' => $this->getUserDisplayName($token, $id),
|
2020-07-01 17:27:50 -04:00
|
|
|
];
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Processes a received access token for a user. Login the user when
|
|
|
|
* they exist, optionally registering them automatically.
|
|
|
|
* @throws OpenIdException
|
|
|
|
* @throws JsonDebugException
|
|
|
|
* @throws UserRegistrationException
|
|
|
|
*/
|
|
|
|
public function processAccessTokenCallback(AccessToken $accessToken): User
|
|
|
|
{
|
|
|
|
$userDetails = $this->getUserDetails($accessToken->getIdToken());
|
|
|
|
$isLoggedIn = auth()->check();
|
|
|
|
|
|
|
|
if ($this->config['dump_user_details']) {
|
|
|
|
throw new JsonDebugException($accessToken->jsonSerialize());
|
|
|
|
}
|
|
|
|
|
|
|
|
if ($userDetails['email'] === null) {
|
|
|
|
throw new OpenIdException(trans('errors.openid_no_email_address'));
|
|
|
|
}
|
|
|
|
|
|
|
|
if ($isLoggedIn) {
|
|
|
|
throw new OpenIdException(trans('errors.openid_already_logged_in'), '/login');
|
|
|
|
}
|
|
|
|
|
|
|
|
$user = $this->getOrRegisterUser($userDetails);
|
|
|
|
if ($user === null) {
|
|
|
|
throw new OpenIdException(trans('errors.openid_user_not_registered', ['name' => $userDetails['external_id']]), '/login');
|
|
|
|
}
|
|
|
|
|
|
|
|
auth()->login($user);
|
2020-07-06 20:26:00 -04:00
|
|
|
session()->put('openid_token', json_encode($accessToken));
|
2020-07-01 17:27:50 -04:00
|
|
|
return $user;
|
|
|
|
}
|
|
|
|
}
|