From 5a204087283f54ab4431ac045eec1044b768580e Mon Sep 17 00:00:00 2001 From: Marijus Kilmanas Date: Wed, 17 Jan 2024 16:09:32 +0200 Subject: [PATCH] feat: Support string concatenation of scopes (#183) ### Changes There has been support for Symfony role resolution from both `permissions` and `scope` claims in the JWT tokens for a while now. However, there was a problem that this bundle expected `scope` claim to be either an array, or a string with the single scope value, while in reality Auth0 authentication API returns tokens with `scope` value being a concatenated string of multiple scope values: Screenshot 2024-01-16 at 15 00 12 In this bundle such scope produced an unusable role code with spaces in it and all permissions in one string. This PR fixes this issue, by adding support for concatenated-string scope value while preserving support for previous formats as well. ### Testing PhpUnit tests added (both previous formats + the new one; i.e. one test would fail on old codebase) [x] This change adds test coverage [ ] This change has been tested on the latest version of Symfony ### Checklist [x] I have read the [Auth0 general contribution guidelines](https://github.com/auth0/open-source-template/blob/master/GENERAL-CONTRIBUTING.md) [x] I have read the [Auth0 Code of Conduct](https://github.com/auth0/open-source-template/blob/master/CODE-OF-CONDUCT.md) [x] All existing and new tests complete without errors --- src/Models/User.php | 2 +- tests/Unit/Models/UserTest.php | 48 ++++++++++++++++++++++++++++++++++ 2 files changed, 49 insertions(+), 1 deletion(-) create mode 100644 tests/Unit/Models/UserTest.php diff --git a/src/Models/User.php b/src/Models/User.php index 920d631..9b659e6 100644 --- a/src/Models/User.php +++ b/src/Models/User.php @@ -254,7 +254,7 @@ public function getRoles(): array $scopes = $this->data['scope'] ?? []; if (is_string($scopes)) { - $scopes = [$scopes]; + $scopes = explode(' ', $scopes); } foreach ($roles as $role) { diff --git a/tests/Unit/Models/UserTest.php b/tests/Unit/Models/UserTest.php new file mode 100644 index 0000000..f6bcd0e --- /dev/null +++ b/tests/Unit/Models/UserTest.php @@ -0,0 +1,48 @@ +getRoles(); + foreach ($expectedRoles as $role) { + $this::assertContains($role, $userRoles); + } + } + + public function testGetRolesWithSingleScope(): void + { + $user = new User([ + 'scope' => 'read:users', + ]); + + $this->assertHasRoles($user, ['ROLE_USER', 'ROLE_READ_USERS']); + } + + public function testGetRolesWithArrayScope(): void + { + $user = new User([ + 'scope' => ['read:users', 'write:users'], + ]); + + $this->assertHasRoles($user, ['ROLE_USER', 'ROLE_READ_USERS', 'ROLE_WRITE_USERS']); + } + + public function testGetRolesWithStringScope(): void + { + $user = new User([ + 'scope' => 'read:users write:users', + ]); + + $this->assertHasRoles($user, ['ROLE_USER', 'ROLE_READ_USERS', 'ROLE_WRITE_USERS']); + } +}