mirror of
https://github.com/BookStackApp/BookStack.git
synced 2025-07-28 17:02:04 +03:00
Added token and key handling elements for oidc jwt
- Got basic signing support and structure checking done. - Need to run through actual claim checking before providing details back to app.
This commit is contained in:
@ -47,7 +47,7 @@ class LoginService
|
||||
|
||||
// Authenticate on all session guards if a likely admin
|
||||
if ($user->can('users-manage') && $user->can('user-roles-manage')) {
|
||||
$guards = ['standard', 'ldap', 'saml2', 'openid'];
|
||||
$guards = ['standard', 'ldap', 'saml2', 'oidc'];
|
||||
foreach ($guards as $guard) {
|
||||
auth($guard)->login($user);
|
||||
}
|
||||
|
8
app/Auth/Access/OpenIdConnect/InvalidKeyException.php
Normal file
8
app/Auth/Access/OpenIdConnect/InvalidKeyException.php
Normal file
@ -0,0 +1,8 @@
|
||||
<?php
|
||||
|
||||
namespace BookStack\Auth\Access\OpenIdConnect;
|
||||
|
||||
class InvalidKeyException extends \Exception
|
||||
{
|
||||
|
||||
}
|
10
app/Auth/Access/OpenIdConnect/InvalidTokenException.php
Normal file
10
app/Auth/Access/OpenIdConnect/InvalidTokenException.php
Normal file
@ -0,0 +1,10 @@
|
||||
<?php
|
||||
|
||||
namespace BookStack\Auth\Access\OpenIdConnect;
|
||||
|
||||
use Exception;
|
||||
|
||||
class InvalidTokenException extends Exception
|
||||
{
|
||||
|
||||
}
|
76
app/Auth/Access/OpenIdConnect/JwtSigningKey.php
Normal file
76
app/Auth/Access/OpenIdConnect/JwtSigningKey.php
Normal file
@ -0,0 +1,76 @@
|
||||
<?php
|
||||
|
||||
namespace BookStack\Auth\Access\OpenIdConnect;
|
||||
|
||||
use phpseclib3\Crypt\Common\PublicKey;
|
||||
use phpseclib3\Crypt\PublicKeyLoader;
|
||||
use phpseclib3\Crypt\RSA;
|
||||
use phpseclib3\Math\BigInteger;
|
||||
|
||||
class JwtSigningKey
|
||||
{
|
||||
/**
|
||||
* @var PublicKey
|
||||
*/
|
||||
protected $key;
|
||||
|
||||
/**
|
||||
* Can be created either from a JWK parameter array or local file path to load a certificate from.
|
||||
* Examples:
|
||||
* 'file:///var/www/cert.pem'
|
||||
* ['kty' => 'RSA', 'alg' => 'RS256', 'n' => 'abc123...']
|
||||
* @param array|string $jwkOrKeyPath
|
||||
* @throws InvalidKeyException
|
||||
*/
|
||||
public function __construct($jwkOrKeyPath)
|
||||
{
|
||||
if (is_array($jwkOrKeyPath)) {
|
||||
$this->loadFromJwkArray($jwkOrKeyPath);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws InvalidKeyException
|
||||
*/
|
||||
protected function loadFromJwkArray(array $jwk)
|
||||
{
|
||||
if ($jwk['alg'] !== 'RS256') {
|
||||
throw new InvalidKeyException("Only RS256 keys are currently supported. Found key using {$jwk['alg']}");
|
||||
}
|
||||
|
||||
if ($jwk['use'] !== 'sig') {
|
||||
throw new InvalidKeyException("Only signature keys are currently supported. Found key for use {$jwk['sig']}");
|
||||
}
|
||||
|
||||
if (empty($jwk['e'] ?? '')) {
|
||||
throw new InvalidKeyException('An "e" parameter on the provided key is expected');
|
||||
}
|
||||
|
||||
if (empty($jwk['n'] ?? '')) {
|
||||
throw new InvalidKeyException('A "n" parameter on the provided key is expected');
|
||||
}
|
||||
|
||||
$n = strtr($jwk['n'] ?? '', '-_', '+/');
|
||||
|
||||
try {
|
||||
/** @var RSA $key */
|
||||
$key = PublicKeyLoader::load([
|
||||
'e' => new BigInteger(base64_decode($jwk['e']), 256),
|
||||
'n' => new BigInteger(base64_decode($n), 256),
|
||||
])->withPadding(RSA::SIGNATURE_PKCS1);
|
||||
|
||||
$this->key = $key;
|
||||
} catch (\Exception $exception) {
|
||||
throw new InvalidKeyException("Failed to load key from JWK parameters with error: {$exception->getMessage()}");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Use this key to sign the given content and return the signature.
|
||||
*/
|
||||
public function verify(string $content, string $signature): bool
|
||||
{
|
||||
return $this->key->verify($content, $signature);
|
||||
}
|
||||
|
||||
}
|
54
app/Auth/Access/OpenIdConnect/OpenIdConnectAccessToken.php
Normal file
54
app/Auth/Access/OpenIdConnect/OpenIdConnectAccessToken.php
Normal file
@ -0,0 +1,54 @@
|
||||
<?php
|
||||
|
||||
namespace BookStack\Auth\Access\OpenIdConnect;
|
||||
|
||||
use InvalidArgumentException;
|
||||
use League\OAuth2\Client\Token\AccessToken;
|
||||
|
||||
class OpenIdConnectAccessToken extends AccessToken
|
||||
{
|
||||
/**
|
||||
* Constructs an access token.
|
||||
*
|
||||
* @param array $options An array of options returned by the service provider
|
||||
* in the access token request. The `access_token` option is required.
|
||||
* @throws InvalidArgumentException if `access_token` is not provided in `$options`.
|
||||
*/
|
||||
public function __construct(array $options = [])
|
||||
{
|
||||
parent::__construct($options);
|
||||
$this->validate($options);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Validate this access token response for OIDC.
|
||||
* As per https://openid.net/specs/openid-connect-basic-1_0.html#TokenOK.
|
||||
*/
|
||||
private function validate(array $options): void
|
||||
{
|
||||
// access_token: REQUIRED. Access Token for the UserInfo Endpoint.
|
||||
// Performed on the extended class
|
||||
|
||||
// token_type: REQUIRED. OAuth 2.0 Token Type value. The value MUST be Bearer, as specified in OAuth 2.0
|
||||
// Bearer Token Usage [RFC6750], for Clients using this subset.
|
||||
// Note that the token_type value is case-insensitive.
|
||||
if (strtolower(($options['token_type'] ?? '')) !== 'bearer') {
|
||||
throw new InvalidArgumentException('The response token type MUST be "Bearer"');
|
||||
}
|
||||
|
||||
// id_token: REQUIRED. ID Token.
|
||||
if (empty($options['id_token'])) {
|
||||
throw new InvalidArgumentException('An "id_token" property must be provided');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the id token value from this access token response.
|
||||
*/
|
||||
public function getIdToken(): string
|
||||
{
|
||||
return $this->getValues()['id_token'];
|
||||
}
|
||||
|
||||
}
|
143
app/Auth/Access/OpenIdConnect/OpenIdConnectIdToken.php
Normal file
143
app/Auth/Access/OpenIdConnect/OpenIdConnectIdToken.php
Normal file
@ -0,0 +1,143 @@
|
||||
<?php
|
||||
|
||||
namespace BookStack\Auth\Access\OpenIdConnect;
|
||||
|
||||
class OpenIdConnectIdToken
|
||||
{
|
||||
/**
|
||||
* @var array
|
||||
*/
|
||||
protected $header;
|
||||
|
||||
/**
|
||||
* @var array
|
||||
*/
|
||||
protected $payload;
|
||||
|
||||
/**
|
||||
* @var string
|
||||
*/
|
||||
protected $signature;
|
||||
|
||||
/**
|
||||
* @var array[]|string[]
|
||||
*/
|
||||
protected $keys;
|
||||
|
||||
/**
|
||||
* @var string
|
||||
*/
|
||||
protected $issuer;
|
||||
|
||||
/**
|
||||
* @var array
|
||||
*/
|
||||
protected $tokenParts = [];
|
||||
|
||||
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.
|
||||
* @throws InvalidTokenException
|
||||
*/
|
||||
public function validate()
|
||||
{
|
||||
$this->validateTokenStructure();
|
||||
$this->validateTokenSignature();
|
||||
$this->validateTokenClaims();
|
||||
}
|
||||
|
||||
/**
|
||||
* 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 InvalidTokenException
|
||||
*/
|
||||
protected function validateTokenStructure(): void
|
||||
{
|
||||
foreach (['header', 'payload'] as $prop) {
|
||||
if (empty($this->$prop) || !is_array($this->$prop)) {
|
||||
throw new InvalidTokenException("Could not parse out a valid {$prop} within the provided token");
|
||||
}
|
||||
}
|
||||
|
||||
if (empty($this->signature) || !is_string($this->signature)) {
|
||||
throw new InvalidTokenException("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 InvalidTokenException
|
||||
*/
|
||||
protected function validateTokenSignature(): void
|
||||
{
|
||||
if ($this->header['alg'] !== 'RS256') {
|
||||
throw new InvalidTokenException("Only RS256 signature validation is supported. Token reports using {$this->header['alg']}");
|
||||
}
|
||||
|
||||
$parsedKeys = array_map(function($key) {
|
||||
try {
|
||||
return new JwtSigningKey($key);
|
||||
} catch (InvalidKeyException $e) {
|
||||
return null;
|
||||
}
|
||||
}, $this->keys);
|
||||
|
||||
$parsedKeys = array_filter($parsedKeys);
|
||||
|
||||
$contentToSign = $this->tokenParts[0] . '.' . $this->tokenParts[1];
|
||||
foreach ($parsedKeys as $parsedKey) {
|
||||
if ($parsedKey->verify($contentToSign, $this->signature)) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
throw new InvalidTokenException('Token signature could not be validated using the provided keys.');
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate the claims of the token.
|
||||
* As per https://openid.net/specs/openid-connect-basic-1_0.html#IDTokenValidation
|
||||
*/
|
||||
protected function validateTokenClaims(): void
|
||||
{
|
||||
// TODO
|
||||
}
|
||||
|
||||
}
|
@ -1,7 +1,8 @@
|
||||
<?php
|
||||
|
||||
namespace BookStack\Auth\Access;
|
||||
namespace BookStack\Auth\Access\OpenIdConnect;
|
||||
|
||||
use League\OAuth2\Client\Grant\AbstractGrant;
|
||||
use League\OAuth2\Client\Provider\AbstractProvider;
|
||||
use League\OAuth2\Client\Provider\Exception\IdentityProviderException;
|
||||
use League\OAuth2\Client\Provider\GenericResourceOwner;
|
||||
@ -106,4 +107,21 @@ class OpenIdConnectOAuthProvider extends AbstractProvider
|
||||
{
|
||||
return new GenericResourceOwner($response, '');
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates an access token from a response.
|
||||
*
|
||||
* The grant that was used to fetch the response can be used to provide
|
||||
* additional context.
|
||||
*
|
||||
* @param array $response
|
||||
* @param AbstractGrant $grant
|
||||
* @return OpenIdConnectAccessToken
|
||||
*/
|
||||
protected function createAccessToken(array $response, AbstractGrant $grant)
|
||||
{
|
||||
return new OpenIdConnectAccessToken($response);
|
||||
}
|
||||
|
||||
|
||||
}
|
@ -1,5 +1,8 @@
|
||||
<?php namespace BookStack\Auth\Access;
|
||||
<?php namespace BookStack\Auth\Access\OpenIdConnect;
|
||||
|
||||
use BookStack\Auth\Access\LoginService;
|
||||
use BookStack\Auth\Access\OpenIdConnect\OpenIdConnectOAuthProvider;
|
||||
use BookStack\Auth\Access\RegistrationService;
|
||||
use BookStack\Auth\User;
|
||||
use BookStack\Exceptions\JsonDebugException;
|
||||
use BookStack\Exceptions\OpenIdConnectException;
|
||||
@ -8,6 +11,11 @@ use BookStack\Exceptions\UserRegistrationException;
|
||||
use Exception;
|
||||
use Lcobucci\JWT\Token;
|
||||
use League\OAuth2\Client\Token\AccessToken;
|
||||
use function auth;
|
||||
use function config;
|
||||
use function dd;
|
||||
use function trans;
|
||||
use function url;
|
||||
|
||||
/**
|
||||
* Class OpenIdConnectService
|
||||
@ -122,17 +130,21 @@ class OpenIdConnectService
|
||||
* @throws UserRegistrationException
|
||||
* @throws StoppedAuthenticationException
|
||||
*/
|
||||
protected function processAccessTokenCallback(AccessToken $accessToken): User
|
||||
protected function processAccessTokenCallback(OpenIdConnectAccessToken $accessToken): User
|
||||
{
|
||||
dd($accessToken->getValues());
|
||||
$idTokenText = $accessToken->getIdToken();
|
||||
$idToken = new OpenIdConnectIdToken(
|
||||
$idTokenText,
|
||||
$this->config['issuer'],
|
||||
[$this->config['jwt_public_key']]
|
||||
);
|
||||
|
||||
// TODO - Create a class to manage token parsing and validation on this
|
||||
// Using the config params:
|
||||
// $this->config['jwt_public_key']
|
||||
// $this->config['issuer']
|
||||
//
|
||||
// Ensure ID token validation is done:
|
||||
// https://openid.net/specs/openid-connect-basic-1_0.html#IDTokenValidation
|
||||
// To full affect and tested
|
||||
// JWT signature algorthims:
|
||||
// https://datatracker.ietf.org/doc/html/rfc7518#section-3
|
||||
|
||||
$userDetails = $this->getUserDetails($accessToken->getIdToken());
|
||||
$isLoggedIn = auth()->check();
|
Reference in New Issue
Block a user