mirror of
https://github.com/BookStackApp/BookStack.git
synced 2024-10-01 01:36:00 -04:00
OIDC Userinfo: Added JWT signed response support
Not yet tested, nor checked all response validations.
This commit is contained in:
parent
fa543bbd4d
commit
b18cee3dc4
@ -2,58 +2,8 @@
|
|||||||
|
|
||||||
namespace BookStack\Access\Oidc;
|
namespace BookStack\Access\Oidc;
|
||||||
|
|
||||||
class OidcIdToken implements ProvidesClaims
|
class OidcIdToken extends OidcJwtWithClaims implements ProvidesClaims
|
||||||
{
|
{
|
||||||
protected array $header;
|
|
||||||
protected array $payload;
|
|
||||||
protected string $signature;
|
|
||||||
protected string $issuer;
|
|
||||||
protected array $tokenParts = [];
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @var array[]|string[]
|
|
||||||
*/
|
|
||||||
protected array $keys;
|
|
||||||
|
|
||||||
public function __construct(string $token, string $issuer, array $keys)
|
|
||||||
{
|
|
||||||
$this->keys = $keys;
|
|
||||||
$this->issuer = $issuer;
|
|
||||||
$this->parse($token);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Parse the token content into its components.
|
|
||||||
*/
|
|
||||||
protected function parse(string $token): void
|
|
||||||
{
|
|
||||||
$this->tokenParts = explode('.', $token);
|
|
||||||
$this->header = $this->parseEncodedTokenPart($this->tokenParts[0]);
|
|
||||||
$this->payload = $this->parseEncodedTokenPart($this->tokenParts[1] ?? '');
|
|
||||||
$this->signature = $this->base64UrlDecode($this->tokenParts[2] ?? '') ?: '';
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Parse a Base64-JSON encoded token part.
|
|
||||||
* Returns the data as a key-value array or empty array upon error.
|
|
||||||
*/
|
|
||||||
protected function parseEncodedTokenPart(string $part): array
|
|
||||||
{
|
|
||||||
$json = $this->base64UrlDecode($part) ?: '{}';
|
|
||||||
$decoded = json_decode($json, true);
|
|
||||||
|
|
||||||
return is_array($decoded) ? $decoded : [];
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Base64URL decode. Needs some character conversions to be compatible
|
|
||||||
* with PHP's default base64 handling.
|
|
||||||
*/
|
|
||||||
protected function base64UrlDecode(string $encoded): string
|
|
||||||
{
|
|
||||||
return base64_decode(strtr($encoded, '-_', '+/'));
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Validate all possible parts of the id token.
|
* Validate all possible parts of the id token.
|
||||||
*
|
*
|
||||||
@ -61,89 +11,12 @@ class OidcIdToken implements ProvidesClaims
|
|||||||
*/
|
*/
|
||||||
public function validate(string $clientId): bool
|
public function validate(string $clientId): bool
|
||||||
{
|
{
|
||||||
$this->validateTokenStructure();
|
parent::validateCommonClaims();
|
||||||
$this->validateTokenSignature();
|
|
||||||
$this->validateTokenClaims($clientId);
|
$this->validateTokenClaims($clientId);
|
||||||
|
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Fetch a specific claim from this token.
|
|
||||||
* Returns null if it is null or does not exist.
|
|
||||||
*/
|
|
||||||
public function getClaim(string $claim): mixed
|
|
||||||
{
|
|
||||||
return $this->payload[$claim] ?? null;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Get all returned claims within the token.
|
|
||||||
*/
|
|
||||||
public function getAllClaims(): array
|
|
||||||
{
|
|
||||||
return $this->payload;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Replace the existing claim data of this token with that provided.
|
|
||||||
*/
|
|
||||||
public function replaceClaims(array $claims): void
|
|
||||||
{
|
|
||||||
$this->payload = $claims;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Validate the structure of the given token and ensure we have the required pieces.
|
|
||||||
* As per https://datatracker.ietf.org/doc/html/rfc7519#section-7.2.
|
|
||||||
*
|
|
||||||
* @throws OidcInvalidTokenException
|
|
||||||
*/
|
|
||||||
protected function validateTokenStructure(): void
|
|
||||||
{
|
|
||||||
foreach (['header', 'payload'] as $prop) {
|
|
||||||
if (empty($this->$prop) || !is_array($this->$prop)) {
|
|
||||||
throw new OidcInvalidTokenException("Could not parse out a valid {$prop} within the provided token");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (empty($this->signature) || !is_string($this->signature)) {
|
|
||||||
throw new OidcInvalidTokenException('Could not parse out a valid signature within the provided token');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Validate the signature of the given token and ensure it validates against the provided key.
|
|
||||||
*
|
|
||||||
* @throws OidcInvalidTokenException
|
|
||||||
*/
|
|
||||||
protected function validateTokenSignature(): void
|
|
||||||
{
|
|
||||||
if ($this->header['alg'] !== 'RS256') {
|
|
||||||
throw new OidcInvalidTokenException("Only RS256 signature validation is supported. Token reports using {$this->header['alg']}");
|
|
||||||
}
|
|
||||||
|
|
||||||
$parsedKeys = array_map(function ($key) {
|
|
||||||
try {
|
|
||||||
return new OidcJwtSigningKey($key);
|
|
||||||
} catch (OidcInvalidKeyException $e) {
|
|
||||||
throw new OidcInvalidTokenException('Failed to read signing key with error: ' . $e->getMessage());
|
|
||||||
}
|
|
||||||
}, $this->keys);
|
|
||||||
|
|
||||||
$parsedKeys = array_filter($parsedKeys);
|
|
||||||
|
|
||||||
$contentToSign = $this->tokenParts[0] . '.' . $this->tokenParts[1];
|
|
||||||
/** @var OidcJwtSigningKey $parsedKey */
|
|
||||||
foreach ($parsedKeys as $parsedKey) {
|
|
||||||
if ($parsedKey->verify($contentToSign, $this->signature)) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
throw new OidcInvalidTokenException('Token signature could not be validated using the provided keys');
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Validate the claims of the token.
|
* Validate the claims of the token.
|
||||||
* As per https://openid.net/specs/openid-connect-basic-1_0.html#IDTokenValidation.
|
* As per https://openid.net/specs/openid-connect-basic-1_0.html#IDTokenValidation.
|
||||||
@ -154,27 +27,18 @@ class OidcIdToken implements ProvidesClaims
|
|||||||
{
|
{
|
||||||
// 1. The Issuer Identifier for the OpenID Provider (which is typically obtained during Discovery)
|
// 1. The Issuer Identifier for the OpenID Provider (which is typically obtained during Discovery)
|
||||||
// MUST exactly match the value of the iss (issuer) Claim.
|
// MUST exactly match the value of the iss (issuer) Claim.
|
||||||
if (empty($this->payload['iss']) || $this->issuer !== $this->payload['iss']) {
|
// Already done in parent.
|
||||||
throw new OidcInvalidTokenException('Missing or non-matching token issuer value');
|
|
||||||
}
|
|
||||||
|
|
||||||
// 2. The Client MUST validate that the aud (audience) Claim contains its client_id value registered
|
// 2. The Client MUST validate that the aud (audience) Claim contains its client_id value registered
|
||||||
// at the Issuer identified by the iss (issuer) Claim as an audience. The ID Token MUST be rejected
|
// at the Issuer identified by the iss (issuer) Claim as an audience. The ID Token MUST be rejected
|
||||||
// if the ID Token does not list the Client as a valid audience, or if it contains additional
|
// if the ID Token does not list the Client as a valid audience, or if it contains additional
|
||||||
// audiences not trusted by the Client.
|
// audiences not trusted by the Client.
|
||||||
if (empty($this->payload['aud'])) {
|
// Partially done in parent.
|
||||||
throw new OidcInvalidTokenException('Missing token audience value');
|
|
||||||
}
|
|
||||||
|
|
||||||
$aud = is_string($this->payload['aud']) ? [$this->payload['aud']] : $this->payload['aud'];
|
$aud = is_string($this->payload['aud']) ? [$this->payload['aud']] : $this->payload['aud'];
|
||||||
if (count($aud) !== 1) {
|
if (count($aud) !== 1) {
|
||||||
throw new OidcInvalidTokenException('Token audience value has ' . count($aud) . ' values, Expected 1');
|
throw new OidcInvalidTokenException('Token audience value has ' . count($aud) . ' values, Expected 1');
|
||||||
}
|
}
|
||||||
|
|
||||||
if ($aud[0] !== $clientId) {
|
|
||||||
throw new OidcInvalidTokenException('Token audience value did not match the expected client_id');
|
|
||||||
}
|
|
||||||
|
|
||||||
// 3. If the ID Token contains multiple audiences, the Client SHOULD verify that an azp Claim is present.
|
// 3. If the ID Token contains multiple audiences, the Client SHOULD verify that an azp Claim is present.
|
||||||
// NOTE: Addressed by enforcing a count of 1 above.
|
// NOTE: Addressed by enforcing a count of 1 above.
|
||||||
|
|
||||||
|
174
app/Access/Oidc/OidcJwtWithClaims.php
Normal file
174
app/Access/Oidc/OidcJwtWithClaims.php
Normal file
@ -0,0 +1,174 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace BookStack\Access\Oidc;
|
||||||
|
|
||||||
|
class OidcJwtWithClaims implements ProvidesClaims
|
||||||
|
{
|
||||||
|
protected array $header;
|
||||||
|
protected array $payload;
|
||||||
|
protected string $signature;
|
||||||
|
protected string $issuer;
|
||||||
|
protected array $tokenParts = [];
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @var array[]|string[]
|
||||||
|
*/
|
||||||
|
protected array $keys;
|
||||||
|
|
||||||
|
public function __construct(string $token, string $issuer, array $keys)
|
||||||
|
{
|
||||||
|
$this->keys = $keys;
|
||||||
|
$this->issuer = $issuer;
|
||||||
|
$this->parse($token);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Parse the token content into its components.
|
||||||
|
*/
|
||||||
|
protected function parse(string $token): void
|
||||||
|
{
|
||||||
|
$this->tokenParts = explode('.', $token);
|
||||||
|
$this->header = $this->parseEncodedTokenPart($this->tokenParts[0]);
|
||||||
|
$this->payload = $this->parseEncodedTokenPart($this->tokenParts[1] ?? '');
|
||||||
|
$this->signature = $this->base64UrlDecode($this->tokenParts[2] ?? '') ?: '';
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Parse a Base64-JSON encoded token part.
|
||||||
|
* Returns the data as a key-value array or empty array upon error.
|
||||||
|
*/
|
||||||
|
protected function parseEncodedTokenPart(string $part): array
|
||||||
|
{
|
||||||
|
$json = $this->base64UrlDecode($part) ?: '{}';
|
||||||
|
$decoded = json_decode($json, true);
|
||||||
|
|
||||||
|
return is_array($decoded) ? $decoded : [];
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Base64URL decode. Needs some character conversions to be compatible
|
||||||
|
* with PHP's default base64 handling.
|
||||||
|
*/
|
||||||
|
protected function base64UrlDecode(string $encoded): string
|
||||||
|
{
|
||||||
|
return base64_decode(strtr($encoded, '-_', '+/'));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Validate common parts of OIDC JWT tokens.
|
||||||
|
*
|
||||||
|
* @throws OidcInvalidTokenException
|
||||||
|
*/
|
||||||
|
protected function validateCommonTokenDetails(): bool
|
||||||
|
{
|
||||||
|
$this->validateTokenStructure();
|
||||||
|
$this->validateTokenSignature();
|
||||||
|
$this->validateCommonClaims();
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Fetch a specific claim from this token.
|
||||||
|
* Returns null if it is null or does not exist.
|
||||||
|
*/
|
||||||
|
public function getClaim(string $claim): mixed
|
||||||
|
{
|
||||||
|
return $this->payload[$claim] ?? null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get all returned claims within the token.
|
||||||
|
*/
|
||||||
|
public function getAllClaims(): array
|
||||||
|
{
|
||||||
|
return $this->payload;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Replace the existing claim data of this token with that provided.
|
||||||
|
*/
|
||||||
|
public function replaceClaims(array $claims): void
|
||||||
|
{
|
||||||
|
$this->payload = $claims;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Validate the structure of the given token and ensure we have the required pieces.
|
||||||
|
* As per https://datatracker.ietf.org/doc/html/rfc7519#section-7.2.
|
||||||
|
*
|
||||||
|
* @throws OidcInvalidTokenException
|
||||||
|
*/
|
||||||
|
protected function validateTokenStructure(): void
|
||||||
|
{
|
||||||
|
foreach (['header', 'payload'] as $prop) {
|
||||||
|
if (empty($this->$prop) || !is_array($this->$prop)) {
|
||||||
|
throw new OidcInvalidTokenException("Could not parse out a valid {$prop} within the provided token");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (empty($this->signature) || !is_string($this->signature)) {
|
||||||
|
throw new OidcInvalidTokenException('Could not parse out a valid signature within the provided token');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Validate the signature of the given token and ensure it validates against the provided key.
|
||||||
|
*
|
||||||
|
* @throws OidcInvalidTokenException
|
||||||
|
*/
|
||||||
|
protected function validateTokenSignature(): void
|
||||||
|
{
|
||||||
|
if ($this->header['alg'] !== 'RS256') {
|
||||||
|
throw new OidcInvalidTokenException("Only RS256 signature validation is supported. Token reports using {$this->header['alg']}");
|
||||||
|
}
|
||||||
|
|
||||||
|
$parsedKeys = array_map(function ($key) {
|
||||||
|
try {
|
||||||
|
return new OidcJwtSigningKey($key);
|
||||||
|
} catch (OidcInvalidKeyException $e) {
|
||||||
|
throw new OidcInvalidTokenException('Failed to read signing key with error: ' . $e->getMessage());
|
||||||
|
}
|
||||||
|
}, $this->keys);
|
||||||
|
|
||||||
|
$parsedKeys = array_filter($parsedKeys);
|
||||||
|
|
||||||
|
$contentToSign = $this->tokenParts[0] . '.' . $this->tokenParts[1];
|
||||||
|
/** @var OidcJwtSigningKey $parsedKey */
|
||||||
|
foreach ($parsedKeys as $parsedKey) {
|
||||||
|
if ($parsedKey->verify($contentToSign, $this->signature)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
throw new OidcInvalidTokenException('Token signature could not be validated using the provided keys');
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Validate common claims for OIDC JWT tokens.
|
||||||
|
* As per https://openid.net/specs/openid-connect-basic-1_0.html#IDTokenValidation
|
||||||
|
* and https://openid.net/specs/openid-connect-core-1_0.html#UserInfoResponse
|
||||||
|
*
|
||||||
|
* @throws OidcInvalidTokenException
|
||||||
|
*/
|
||||||
|
public function validateCommonClaims(): void
|
||||||
|
{
|
||||||
|
// 1. The Issuer Identifier for the OpenID Provider (which is typically obtained during Discovery)
|
||||||
|
// MUST exactly match the value of the iss (issuer) Claim.
|
||||||
|
if (empty($this->payload['iss']) || $this->issuer !== $this->payload['iss']) {
|
||||||
|
throw new OidcInvalidTokenException('Missing or non-matching token issuer value');
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2. The Client MUST validate that the aud (audience) Claim contains its client_id value registered
|
||||||
|
// at the Issuer identified by the iss (issuer) Claim as an audience. The ID Token MUST be rejected
|
||||||
|
// if the ID Token does not list the Client as a valid audience.
|
||||||
|
if (empty($this->payload['aud'])) {
|
||||||
|
throw new OidcInvalidTokenException('Missing token audience value');
|
||||||
|
}
|
||||||
|
|
||||||
|
$aud = is_string($this->payload['aud']) ? [$this->payload['aud']] : $this->payload['aud'];
|
||||||
|
if (!in_array($this->payload['aud'], $aud, true)) {
|
||||||
|
throw new OidcInvalidTokenException('Token audience value did not match the expected client_id');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
@ -246,7 +246,11 @@ class OidcService
|
|||||||
if (!$userDetails->isFullyPopulated($this->shouldSyncGroups()) && !empty($settings->userinfoEndpoint)) {
|
if (!$userDetails->isFullyPopulated($this->shouldSyncGroups()) && !empty($settings->userinfoEndpoint)) {
|
||||||
$provider = $this->getProvider($settings);
|
$provider = $this->getProvider($settings);
|
||||||
$request = $provider->getAuthenticatedRequest('GET', $settings->userinfoEndpoint, $accessToken->getToken());
|
$request = $provider->getAuthenticatedRequest('GET', $settings->userinfoEndpoint, $accessToken->getToken());
|
||||||
$response = new OidcUserinfoResponse($provider->getResponse($request));
|
$response = new OidcUserinfoResponse(
|
||||||
|
$provider->getResponse($request),
|
||||||
|
$settings->issuer,
|
||||||
|
$settings->keys,
|
||||||
|
);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
$response->validate($idToken->getClaim('sub'));
|
$response->validate($idToken->getClaim('sub'));
|
||||||
|
@ -7,14 +7,20 @@ use Psr\Http\Message\ResponseInterface;
|
|||||||
class OidcUserinfoResponse implements ProvidesClaims
|
class OidcUserinfoResponse implements ProvidesClaims
|
||||||
{
|
{
|
||||||
protected array $claims = [];
|
protected array $claims = [];
|
||||||
|
protected ?OidcJwtWithClaims $jwt = null;
|
||||||
|
|
||||||
public function __construct(ResponseInterface $response)
|
public function __construct(ResponseInterface $response, string $issuer, array $keys)
|
||||||
{
|
{
|
||||||
if ($response->getHeader('Content-Type')[0] === 'application/json') {
|
$contentType = $response->getHeader('Content-Type')[0];
|
||||||
|
if ($contentType === 'application/json') {
|
||||||
$this->claims = json_decode($response->getBody()->getContents(), true);
|
$this->claims = json_decode($response->getBody()->getContents(), true);
|
||||||
}
|
}
|
||||||
|
|
||||||
// TODO - Support JWTs
|
if ($contentType === 'application/jwt') {
|
||||||
|
$this->jwt = new OidcJwtWithClaims($response->getBody()->getContents(), $issuer, $keys);
|
||||||
|
$this->claims = $this->jwt->getAllClaims();
|
||||||
|
}
|
||||||
|
|
||||||
// TODO - Response validation (5.3.4):
|
// TODO - Response validation (5.3.4):
|
||||||
// TODO - Verify that the OP that responded was the intended OP through a TLS server certificate check, per RFC 6125 [RFC6125].
|
// TODO - Verify that the OP that responded was the intended OP through a TLS server certificate check, per RFC 6125 [RFC6125].
|
||||||
// TODO - If the Client has provided a userinfo_encrypted_response_alg parameter during Registration, decrypt the UserInfo Response using the keys specified during Registration.
|
// TODO - If the Client has provided a userinfo_encrypted_response_alg parameter during Registration, decrypt the UserInfo Response using the keys specified during Registration.
|
||||||
@ -26,6 +32,10 @@ class OidcUserinfoResponse implements ProvidesClaims
|
|||||||
*/
|
*/
|
||||||
public function validate(string $idTokenSub): bool
|
public function validate(string $idTokenSub): bool
|
||||||
{
|
{
|
||||||
|
if (!is_null($this->jwt)) {
|
||||||
|
$this->jwt->validateCommonClaims();
|
||||||
|
}
|
||||||
|
|
||||||
$sub = $this->getClaim('sub');
|
$sub = $this->getClaim('sub');
|
||||||
|
|
||||||
// Spec: v1.0 5.3.2: The sub (subject) Claim MUST always be returned in the UserInfo Response.
|
// Spec: v1.0 5.3.2: The sub (subject) Claim MUST always be returned in the UserInfo Response.
|
||||||
|
Loading…
Reference in New Issue
Block a user