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 17, 2024
1 parent 347a969 commit ed511bc
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 10 deletions.
3 changes: 2 additions & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,8 @@
"prefer-stable": true,
"require": {
"firebase/php-jwt": "^6.3",
"php": "^8.0"
"php": "^8.0",
"ext-openssl": "*"
},
"autoload": {
"psr-4": {
Expand Down
24 changes: 15 additions & 9 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,19 @@ 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 = time();
$exp = time() + 300;
$resourceAccess = [config('keycloak.allowed_resources') => []];

$token = JWT::encode($payload, $privateKey, 'RS256');
$principal = Config::get('keycloak.token_principal_attribute');
$credential = Config::get('keycloak.user_provider_credential');
$payload = array_merge([
'iat' => $iat,
'exp' => $exp,
$principal => is_string($user) ? $user : $user->$credential ?? config('keycloak.preferred_username'),
'resource_access' => $resourceAccess
], $payload);

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

0 comments on commit ed511bc

Please sign in to comment.