首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何同时查询samaaccountname和用户主体名symfonyLdap

如何同时查询samaaccountname和用户主体名symfonyLdap
EN

Stack Overflow用户
提问于 2019-07-17 02:57:02
回答 1查看 589关注 0票数 0

我有一个Symfony登录表单对Ldap服务器进行身份验证。在我的配置设置中,我可以使用samaccountname或userprincipalname和uid密钥成功地查询和验证用户。我希望能够允许用户输入他们的用户名或username@domain.com

我在LdapUserProviderClass的loadUserbyUsername()方法中对用户名尝试了一个preg_replace (我知道这并不理想)。它接受用户名,比如username@domain.com,然后传递用户名。我能够验证从Ldap服务器返回了正确的用户,但我仍然返回到登录表单,并带有“无效凭据”。我相信在AuthenticationUtils类请求中发生这种情况的原因是,请求中的用户名仍然是username@domain.com,这与来自Ldap身份验证的user对象中的用户名不匹配。如果有人有关于如何实现允许根据Ldap对username@domain.com和用户名进行身份验证的建议,我将不胜感激。

SecurityController.php

 public function login(Request $request, AuthenticationUtils $authenticationUtils): Response
{


    // get the login error if there is one
    $error = $authenticationUtils->getLastAuthenticationError();
    // last username entered by the user
    $lastUsername = $authenticationUtils->getLastUsername();

    $newLastUsername = trim(preg_replace('/@.*/', '',$lastUsername));

    return $this->render('security/login.html.twig', ['last_username' => $newLastUsername, 'error' => $error]);
}

security.yml

 providers:
        dsg_ldap:
        ldap:
            service: Symfony\Component\Ldap\Ldap
            base_dn: '%env(BASE_DSN)%'
            search_dn: '%env(SEARCH_DN)%'
            search_password: '%env(SEARCH_PWD)%'
            uid_key: '%env(UID_KEY)%'
            #filter: '({uid_key}={_username})'
            default_roles: ROLE_USER
firewalls:
    dev:
        pattern: ^/(_(profiler|wdt)|css|images|js)/
        security: false
    main:
        anonymous: ~

        form_login_ldap:
            login_path: login
            check_path: login
            service: Symfony\Component\Ldap\Ldap
            provider: dsg_ldap
            dn_string: '%env(DN_STRING)%\{username}'

我的LdapUserProvider.php

    class LdapUserProvider extends SymfonyLdapUserProvider
{
    /** @var array maps ldap groups to roles */
    private $groupMapping = [
        '**' => '**',
        '**' => '**',
        '**' => '**',
        '**' => '**'

    ];

    /** @var string extracts group name from dn string */
      private $groupNameRegExp = '/CN=(.+?),/';

    protected function loadUser($username, Entry $entry)
    {
        $roles = ['ROLE_USER'];
        // Check if the entry has attribute with the group
        if (!$entry->hasAttribute('memberOf')) {
            return new User($username, '', $roles);
        }

        // Iterate through each group entry line
        foreach ($entry->getAttribute('memberOf') as $groupLine) {
            // Extract the group name from the line
            $groupName = $this->getGroupName($groupLine);
            // Check if the group is in the mapping
            if (array_key_exists($groupName, $this->groupMapping)) {
                // Map the group to the role(s) the user will have
                $roles[] = $this->groupMapping[$groupName];
            }
        }


        // Create and return the user object
        return new User($username, null, $roles);
    }

    /**
     * Get the group name from the DN
     * @param string $dn
     * @return string
     */
    private function getGroupName($dn)
    {
        $matches = [];
        return preg_match($this->groupNameRegExp, $dn, $matches) ? $matches[1] : '';
    }
}

Symfony\Component\Security\Core\User\LdapUserProvider.php

 public function loadUserByUsername($username)
{

    try {
        $this->ldap->bind($this->searchDn, $this->searchPassword);
        // what i added
        $username = trim(preg_replace('/@.*/', '',$username));
        $username = $this->ldap->escape($username, '', LdapInterface::ESCAPE_FILTER);
        $query = str_replace('{username}', $username, $this->defaultSearch);
        $search = $this->ldap->query($this->baseDn, $query);
    } catch (ConnectionException $e) {
        throw new UsernameNotFoundException(sprintf('User "%s" not found.', $username), 0, $e);
    }

    $entries = $search->execute();
    $count = \count($entries);

    if (!$count) {
        throw new UsernameNotFoundException(sprintf('User "%s" not found.', $username));
    }

    if ($count > 1) {
        throw new UsernameNotFoundException('More than one user found');
    }

    $entry = $entries[0];

    try {
        if (null !== $this->uidKey) {
            $username = $this->getAttributeValue($entry, $this->uidKey);
        }
    } catch (InvalidArgumentException $e) {
    }

    return $this->loadUser($username, $entry);
}
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57063805

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档