Add Roles to User after LDAP connexion on symfony’s project

I have done an LDAP authenticator for my website in symfony 5.

Authentication works perfectly and the user has "ROLE_USER" as role.
But, if this user is in the admin group (on LDAP) he needs to have "ROLE_SUPER_ADMIN".

I tried to use : addRole() – But it doesn’t work.

So can you help me with this ? How can I modify my code to add role to an user ? Thx guys

# app/config/services.yaml

# This file is the entry point to configure your own services.
# Files in the packages/ subdirectory configure your dependencies.

# Put parameters here that don't need to change on each machine where the app is deployed
# https://symfony.com/doc/current/best_practices/configuration.html#application-related-configuration
parameters:

services:
    # default configuration for services in *this* file
    _defaults:
        autowire: true      # Automatically injects dependencies in your services.
        autoconfigure: true # Automatically registers your services as commands, event subscribers, etc.

    SymfonyComponentLdapLdap:
        arguments: ['@SymfonyComponentLdapAdapterExtLdapAdapter']
    SymfonyComponentLdapAdapterExtLdapAdapter:
        arguments:
            -   host: ldap.example.com
                port: 389
                #encryption: tls
                options:
                    protocol_version: 3
                    referrals: false

    # makes classes in src/ available to be used as services
    # this creates a service per class whose id is the fully-qualified class name
    App:
        resource: '../src/*'
        exclude: '../src/{DependencyInjection,Entity,Migrations,Tests,Kernel.php}'

    # controllers are imported separately to make sure services can be injected
    # as action arguments even if you don't extend any base controller class
    AppController:
        resource: '../src/Controller'
        tags: ['controller.service_arguments']

    # add more service definitions when explicit configuration is needed
    # please note that last definitions always *replace* previous ones
# app/config/packages/security.yaml

security:
    # https://symfony.com/doc/current/security.html#where-do-users-come-from-user-providers
    providers:
        my_ldap:
            ldap:
                service: SymfonyComponentLdapLdap
                base_dn: dc=example,dc=com
                search_dn: cn=username,ou=Administration,dc=example,dc=com
                search_password: userPassword
                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: SymfonyComponentLdapLdap
                dn_string: ou=aGroupWhereAreMyUsers,dc=example,dc=com
                query_string: '(samaccountname={username})'
                search_dn: cn=username,ou=Administration,dc=example,dc=com
                search_password: userPassword
            
            logout:
                path: app_logout
        
    access_control:
        - { path: ^/$, roles: IS_AUTHENTICATED_ANONYMOUSLY }
        - { path: ^/info$, roles: ROLE_USER }
//app/src/Controller/defaultController.php

<?php

namespace AppController;

use SymfonyBundleFrameworkBundleControllerAbstractController;
use SymfonyComponentRoutingAnnotationRoute;
use SymfonyComponentHttpFoundationRequest;
use SymfonyComponentHttpFoundationResponse;
use SymfonyComponentSecurityHttpAuthenticationAuthenticationUtils;
 

class DefaultController extends AbstractController
{
    /**
     * @Route("/info", name="default")
     */
    public function index()
    {
        return $this->render('default/index.html.twig', [
            'controller_name' => 'DefaultController',
            'user' => $this->getUser(),
        ]);
    }

    /**
     * @Route("/", name="login")
     */
    public function loginAction(Request $request, AuthenticationUtils $authUtils): Response
    {
        // get the login error if there is one
        $error = $authUtils->getLastAuthenticationError();
        
        // last username entered by the user
        $lastUsername = $authUtils->getLastUsername();

        if(!is_null($this->getUser()) && in_array('CN=userHasToBeInThisGroupToAccessToTheWebsite,OU=Administration,DC=example,DC=com', $this->getUser()->getEntry()->getAttributes()['memberOf'])){

            if(in_array('CN=groupWhereUsersWhoAreInAreAdmins,OU=Administration,DC=example,DC=com', $this->getUser()->getEntry()->getAttributes()['memberOf'])){
                //Insert the code here to add "ROLE_SUPER_ADMIN" to the user before he goes on the dashboard
            }

            return $this->redirectToRoute('default');
        }


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

    /**
     * @Route("/logout", name="app_logout")
     */
    public function logout()
    {
        // controller can be blank: it will never be executed!
        throw new Exception('Don't forget to activate logout in security.yaml');
    }

}
{# app/templates/security/login.html.twig #}

{% extends 'base.html.twig' %}
 
{% block body %}
    {% if error %}
        <div class="alert alert-danger">{{ error.messageKey|trans(error.messageData, 'security') }}</div>
    {% endif %}
     
    <form method="post">
        <label for="username">Username:</label>
        <input type="text" id="username" name="_username" value="{{ last_username }}" required />
     
        <label for="password">Password:</label>
        <input type="password" id="password" name="_password" required />

        <input type="hidden" name="_csrf_token" value="{{ csrf_token('authenticate') }}" />
     
        <button type="submit">login</button>
    </form>

    <a href='/logout'> Logout </a>
{% endblock %}

Source: Symfony Questions

Was this helpful?

0 / 0

Leave a Reply 0

Your email address will not be published. Required fields are marked *