Skip to content

Commit

Permalink
Improve token payload in tests
Browse files Browse the repository at this point in the history
  • Loading branch information
elnurvl committed May 8, 2024
1 parent 347a969 commit c948246
Showing 1 changed file with 27 additions and 7 deletions.
34 changes: 27 additions & 7 deletions src/ActingAsKeycloakUser.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,20 +7,20 @@

trait ActingAsKeycloakUser
{
public function actingAsKeycloakUser($user = null)
public function actingAsKeycloakUser($user = null, $payload = [])
{
if (!$user) {
Config::set('keycloak.load_user_from_database', false);
}

$token = $this->generateKeycloakToken($user);
$token = $this->generateKeycloakToken($user, $payload);

$this->withHeader('Authorization', 'Bearer '.$token);

return $this;
}

public function generateKeycloakToken($user = null)
public function generateKeycloakToken($user = null, $payload = [])
{
$privateKey = openssl_pkey_new([
'digest_alg' => 'sha256',
Expand All @@ -34,13 +34,33 @@ public function generateKeycloakToken($user = null)

Config::set('keycloak.realm_public_key', $publicKey);

$payload = [
'preferred_username' => $user->username ?? config('keycloak.preferred_username'),
'resource_access' => [config('keycloak.allowed_resources') => []]
];
$iat = $this->popByKey($payload, 'iat') ?? time();
$exp = $this->popByKey($payload, 'exp') ?? time() + 300;
$aud = $this->popByKey($payload, 'aud') ?? 'account';
$sub = $this->popByKey($payload, 'sub') ?? $user->id ?? 'php-unit';
$preferredUsername = $this->popByKey($payload, 'preferred_username') ?? $user->username ?? config('keycloak.preferred_username');
$resourceAccess = $this->popByKey($payload, 'resource_access') ?? [config('keycloak.allowed_resources') => []];

$payload = array_merge($payload, [
'iat' => $iat,
'exp' => $exp,
'aud' => $aud,
'sub' => $sub,
'preferred_username' => $preferredUsername,
'resource_access' => $resourceAccess
]);

$token = JWT::encode($payload, $privateKey, 'RS256');

return $token;
}

private function popByKey(&$array, $key) {
if (array_key_exists($key, $array)) {
$value = $array[$key];
unset($array[$key]);
return $value;
}
return null;
}
}

0 comments on commit c948246

Please sign in to comment.