Skip to content

[Security] Ability to add roles in form_login_ldap by ldap group #52181

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

Merged
merged 1 commit into from
Feb 10, 2025
Merged
Show file tree
Hide file tree
Changes from all 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
1 change: 1 addition & 0 deletions src/Symfony/Bundle/SecurityBundle/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ CHANGELOG
* Add encryption support to `OidcTokenHandler` (JWE)
* Add `expose_security_errors` config option to display `AccountStatusException`
* Deprecate the `security.hide_user_not_found` config option in favor of `security.expose_security_errors`
* Add ability to fetch LDAP roles

7.2
---
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ public function create(ContainerBuilder $container, string $id, array $config):
->replaceArgument(1, $config['base_dn'])
->replaceArgument(2, $config['search_dn'])
->replaceArgument(3, $config['search_password'])
->replaceArgument(4, $config['default_roles'])
->replaceArgument(4, $config['role_fetcher'] ? new Reference($config['role_fetcher']) : $config['default_roles'])
->replaceArgument(5, $config['uid_key'])
->replaceArgument(6, $config['filter'])
->replaceArgument(7, $config['password_attribute'])
Expand Down Expand Up @@ -63,6 +63,7 @@ public function addConfiguration(NodeDefinition $node): void
->requiresAtLeastOneElement()
->prototype('scalar')->end()
->end()
->scalarNode('role_fetcher')->defaultNull()->end()
->scalarNode('uid_key')->defaultValue('sAMAccountName')->end()
->scalarNode('filter')->defaultValue('({uid_key}={user_identifier})')->end()
->scalarNode('password_attribute')->defaultNull()->end()
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Bundle\SecurityBundle\Tests\Functional\Bundle\JsonLdapLoginBundle\Controller;

use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\Security\Core\User\UserInterface;

class TestController
{
public function loginCheckAction(UserInterface $user)
{
return new JsonResponse([
'message' => \sprintf('Welcome @%s!', $user->getUserIdentifier()),
'roles' => $user->getRoles(),
]);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Bundle\SecurityBundle\Tests\Functional\Bundle\JsonLdapLoginBundle\Security\Ldap;

use Symfony\Component\Ldap\Entry;
use Symfony\Component\Ldap\Security\RoleFetcherInterface;

class DummyRoleFetcher implements RoleFetcherInterface
{
public function fetchRoles(Entry $entry): array
{
if ($entry->getAttribute('uid') === ['spomky']) {
return ['ROLE_SUPER_ADMIN', 'ROLE_USER'];
}

return ['ROLE_LDAP_USER_42', 'ROLE_USER'];
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,14 @@

namespace Symfony\Bundle\SecurityBundle\Tests\Functional;

use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpKernel\Kernel;
use Symfony\Component\Ldap\Adapter\AdapterInterface;
use Symfony\Component\Ldap\Adapter\CollectionInterface;
use Symfony\Component\Ldap\Adapter\ConnectionInterface;
use Symfony\Component\Ldap\Adapter\ExtLdap\Adapter;
use Symfony\Component\Ldap\Adapter\QueryInterface;
use Symfony\Component\Ldap\Entry;

class JsonLoginLdapTest extends AbstractWebTestCase
{
Expand All @@ -22,4 +29,45 @@ public function testKernelBoot()

$this->assertInstanceOf(Kernel::class, $kernel);
}

public function testDefaultJsonLdapLoginSuccess()
{
if (!interface_exists(\Symfony\Component\Ldap\Security\RoleFetcherInterface::class)) {
$this->markTestSkipped('The "LDAP" component does not support LDAP roles.');
}
// Given
$client = $this->createClient(['test_case' => 'JsonLoginLdap', 'root_config' => 'config.yml', 'debug' => true]);
$container = $client->getContainer();
$connectionMock = $this->createMock(ConnectionInterface::class);
$collection = new class([new Entry('', ['uid' => ['spomky']])]) extends \ArrayObject implements CollectionInterface {
public function toArray(): array
{
return $this->getArrayCopy();
}
};
$queryMock = $this->createMock(QueryInterface::class);
$queryMock
->method('execute')
->willReturn($collection)
;
$ldapAdapterMock = $this->createMock(AdapterInterface::class);
$ldapAdapterMock
->method('getConnection')
->willReturn($connectionMock)
;
$ldapAdapterMock
->method('createQuery')
->willReturn($queryMock)
;
$container->set(Adapter::class, $ldapAdapterMock);

// When
$client->request('POST', '/login', [], [], ['CONTENT_TYPE' => 'application/json'], '{"user": {"login": "spomky", "password": "foo"}}');
$response = $client->getResponse();

// Then
$this->assertInstanceOf(JsonResponse::class, $response);
$this->assertSame(200, $response->getStatusCode());
$this->assertSame(['message' => 'Welcome @spomky!', 'roles' => ['ROLE_SUPER_ADMIN', 'ROLE_USER']], json_decode($response->getContent(), true));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,9 @@ imports:
services:
Symfony\Component\Ldap\Ldap:
arguments: ['@Symfony\Component\Ldap\Adapter\ExtLdap\Adapter']
tags: [ 'ldap' ]
dummy_role_fetcher:
class: Symfony\Bundle\SecurityBundle\Tests\Functional\Bundle\JsonLdapLoginBundle\Security\Ldap\DummyRoleFetcher

Symfony\Component\Ldap\Adapter\ExtLdap\Adapter:
arguments:
Expand All @@ -19,9 +22,8 @@ security:
base_dn: 'dc=onfroy,dc=net'
search_dn: ''
search_password: ''
default_roles: ROLE_USER
role_fetcher: dummy_role_fetcher
uid_key: uid
extra_fields: ['email']

firewalls:
main:
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
login_check:
path: /login
defaults: { _controller: Symfony\Bundle\SecurityBundle\Tests\Functional\Bundle\JsonLdapLoginBundle\Controller\TestController::loginCheckAction }
2 changes: 2 additions & 0 deletions src/Symfony/Component/Ldap/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ CHANGELOG
---

* Deprecate `LdapUser::eraseCredentials()` in favor of `__serialize()`
* Add `RoleFetcherInterface` to allow roles fetching at user loading
* Add ability to fetch LDAP roles

7.2
---
Expand Down
33 changes: 33 additions & 0 deletions src/Symfony/Component/Ldap/Security/AssignDefaultRoles.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Component\Ldap\Security;

use Symfony\Component\Ldap\Entry;

final readonly class AssignDefaultRoles implements RoleFetcherInterface
{
/**
* @param string[] $roles
*/
public function __construct(
private array $roles,
) {
}

/**
* @return string[]
*/
public function fetchRoles(Entry $entry): array
{
return $this->roles;
}
}
8 changes: 6 additions & 2 deletions src/Symfony/Component/Ldap/Security/LdapUserProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -37,13 +37,14 @@ class LdapUserProvider implements UserProviderInterface, PasswordUpgraderInterfa
{
private string $uidKey;
private string $defaultSearch;
private RoleFetcherInterface $roleFetcher;

public function __construct(
private LdapInterface $ldap,
private string $baseDn,
private ?string $searchDn = null,
#[\SensitiveParameter] private ?string $searchPassword = null,
private array $defaultRoles = [],
array|RoleFetcherInterface $defaultRoles = [],
?string $uidKey = null,
?string $filter = null,
private ?string $passwordAttribute = null,
Expand All @@ -54,6 +55,7 @@ public function __construct(

$this->uidKey = $uidKey;
$this->defaultSearch = str_replace('{uid_key}', $uidKey, $filter);
$this->roleFetcher = \is_array($defaultRoles) ? new AssignDefaultRoles($defaultRoles) : $defaultRoles;
}

public function loadUserByIdentifier(string $identifier): UserInterface
Expand Down Expand Up @@ -147,7 +149,9 @@ protected function loadUser(string $identifier, Entry $entry): UserInterface
$extraFields[$field] = $this->getAttributeValue($entry, $field);
}

return new LdapUser($entry, $identifier, $password, $this->defaultRoles, $extraFields);
$roles = $this->roleFetcher->fetchRoles($entry);

return new LdapUser($entry, $identifier, $password, $roles, $extraFields);
}

private function getAttributeValue(Entry $entry, string $attribute): mixed
Expand Down
56 changes: 56 additions & 0 deletions src/Symfony/Component/Ldap/Security/MemberOfRoles.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Component\Ldap\Security;

use Symfony\Component\Ldap\Entry;

final readonly class MemberOfRoles implements RoleFetcherInterface
{
/**
* @param array<string, string> $mapping
*/
public function __construct(
private array $mapping,
private string $attributeName = 'ismemberof',
private string $groupNameRegex = '/^CN=(?P<group>[^,]+),ou.*$/i',
) {
}

/**
* @return string[]
*/
public function fetchRoles(Entry $entry): array
{
if (!$entry->hasAttribute($this->attributeName)) {
return [];
}

$roles = [];
foreach ($entry->getAttribute($this->attributeName) as $group) {
$groupName = $this->getGroupName($group);
if (\array_key_exists($groupName, $this->mapping)) {
$roles[] = $this->mapping[$groupName];
}
}

return array_unique($roles);
}

private function getGroupName(string $group): string
{
if (preg_match($this->groupNameRegex, $group, $matches)) {
return $matches['group'];
}

return $group;
}
}
25 changes: 25 additions & 0 deletions src/Symfony/Component/Ldap/Security/RoleFetcherInterface.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Component\Ldap\Security;

use Symfony\Component\Ldap\Entry;

/**
* Fetches LDAP roles for a given entry.
*/
interface RoleFetcherInterface
{
/**
* @return string[] The list of roles
*/
public function fetchRoles(Entry $entry): array;
}
Loading
Loading