Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improve ActingAsKeycloakUser trait #114

Merged
merged 9 commits into from
May 25, 2024
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 17 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -331,7 +331,7 @@ Auth::hasAnyScope(['scope-f', 'scope-k']) // false

# Acting as a Keycloak user in tests
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Since this is not the main title, we can change it to H2.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Updated the README. Do you think this can be merged followed by release of a new version into packagist this week? I assume it is possible since there is not much change request around the PR, but not sure about your release schedules.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't know about release schedule but since it's not a major version, it can be released ASAP.


As an equivelant feature like `$this->actingAs($user)` in Laravel, with this package you can use `KeycloakGuard\ActingAsKeycloakUser` trait in your test class and then use `actingAsKeycloakUser()` method to act as a user and somehow skip the Keycloak auth:
As an equivalent feature like `$this->actingAs($user)` in Laravel, with this package you can use `KeycloakGuard\ActingAsKeycloakUser` trait in your test class and then use `actingAsKeycloakUser()` method to act as a user and somehow skip the Keycloak auth:

```php
use KeycloakGuard\ActingAsKeycloakUser;
Expand All @@ -346,6 +346,22 @@ public test_a_protected_route()

If you are not using `keycloak.load_user_from_database` option, set `keycloak.preferred_username` with a valid `preferred_username` for tests.

You can also specify exact expectations for the token payload by passing the payload array in the second argument:

```php
use KeycloakGuard\ActingAsKeycloakUser;

public test_a_protected_route()
{
$this->actingAsKeycloakUser($user, [
'aud' => 'account',
'exp' => 1715926026,
'iss' => 'https://localhost:8443/realms/master'
])->getJson('/api/somewhere')
->assertOk();
}
```

# Contribute

You can run this project on VSCODE with Remote Container. Make sure you will use internal VSCODE terminal (inside running container).
Expand Down
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": "*"
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Are you sure is this needed ?

if so , please, use a specific version.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes. The library depends on openssl extension and it is good to specify the requirement so consumers would be aware of it. I cannot be sure of the minimum required version of the extension for this particular library, but even existence of this line should be enough to force consumers installing one of the modern versions.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@robsontenorio , I am not sure if this is the holding part for the PR, but I can remove the line if it bothers you to speed up the release. We are going to release a feature depending on this repository in our project, but cannot make tests pass unless the library allows configuring the test token payload. Therefore, your efforts in merging this PR quickly will be greatly appreciated.

Also I am not sure if it is you or @tuytoosh the reviewer as you are the one assigned for this PR.

},
"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');
}
}
36 changes: 36 additions & 0 deletions tests/AuthenticateTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

namespace KeycloakGuard\Tests;

use Firebase\JWT\JWT;
use Illuminate\Auth\AuthenticationException;
use Illuminate\Hashing\BcryptHasher;
use Illuminate\Support\Facades\Auth;
Expand All @@ -11,6 +12,7 @@
use KeycloakGuard\Exceptions\UserNotFoundException;
use KeycloakGuard\KeycloakGuard;
use KeycloakGuard\Tests\Extensions\CustomUserProvider;
use KeycloakGuard\Tests\Factories\UserFactory;
use KeycloakGuard\Tests\Models\User;
use KeycloakGuard\Token;

Expand Down Expand Up @@ -415,6 +417,40 @@ public function test_with_keycloak_token_trait()
$this->actingAsKeycloakUser($this->user)->json('GET', '/foo/secret');

$this->assertEquals($this->user->username, Auth::user()->username);
$token = Token::decode(request()->bearerToken(), config('keycloak.realm_public_key'), config('keycloak.leeway'), config('keycloak.token_encryption_algorithm'));
$this->assertNotNull($token->iat);
$this->assertNotNull($token->exp);
}

public function test_with_keycloak_token_trait_with_username()
{
$this->actingAsKeycloakUser($this->user->username)->json('GET', '/foo/secret');

$this->assertEquals($this->user->username, Auth::user()->username);
$token = Token::decode(request()->bearerToken(), config('keycloak.realm_public_key'), config('keycloak.leeway'), config('keycloak.token_encryption_algorithm'));
$this->assertNotNull($token->iat);
$this->assertNotNull($token->exp);
}

public function test_with_keycloak_token_trait_with_custom_payload()
{
UserFactory::new()->create([
'username' => 'test_username',
]);
$this->actingAsKeycloakUser($this->user, [
'sub' => 'test_sub',
'aud' => 'test_aud',
'preferred_username' => 'test_username',
'iat' => 12345,
'exp' => 9999999999999,
])->json('GET', '/foo/secret');

$this->assertEquals('test_username', Auth::user()->username);
$token = Token::decode(request()->bearerToken(), config('keycloak.realm_public_key'), config('keycloak.leeway'), config('keycloak.token_encryption_algorithm'));
$this->assertEquals(12345, $token->iat);
$this->assertEquals(9999999999999, $token->exp);
$this->assertEquals('test_sub', $token->sub);
$this->assertEquals('test_aud', $token->aud);
}

public function test_acting_as_keycloak_user_trait_without_user()
Expand Down
Loading