IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

Symfony PHP Discussion :

Aucune vérification ne se fait dans mon loginAction [3.x]


Sujet :

Symfony PHP

  1. #1
    Membre averti
    Homme Profil pro
    Développeur Web
    Inscrit en
    Février 2003
    Messages
    307
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 44
    Localisation : Belgique

    Informations professionnelles :
    Activité : Développeur Web
    Secteur : Administration - Collectivité locale

    Informations forums :
    Inscription : Février 2003
    Messages : 307
    Points : 378
    Points
    378
    Par défaut Aucune vérification ne se fait dans mon loginAction
    Hello

    J'ai mis en place une authentification avec AbstractGuardAuthenticator

    Si l'utilisateur accède à /admin c'est bien la méthode getCredentials qui est appelé et redirige vers /login

    Sur cette page j'ai un formulaire qui pointe vers {{ path('login') }}

    J'ai bien dans mon SecurityController la méthode loginAction qui est appelé

    mais après c'est tout aucune vérification username password ne se fait

    voici mes codes

    service.yml

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
     
    services:
       form_authenticator:
            class: AppBundle\Security\FormAuthenticator
            arguments: ["@router"]
    security.yml

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
     
    security:
     
        encoders:
            AppBundle\Entity\User:
                algorithm: bcrypt
     
        # http://symfony.com/doc/current/book/security.html#where-do-users-come-from-user-providers
        providers:
            user_db_provider:
                entity:
                    class: AppBundle:User
                    property: username
     
        firewalls:
            # disables authentication for assets and the profiler, adapt it according to your needs
            dev:
                pattern: ^/(_(profiler|wdt)|css|images|js)/
                security: false
     
            login_firewall:
                pattern:    ^/login$
                anonymous:  ~
     
            secured_area:
                pattern:    ^/
                anonymous:  ~
                form_login:
                    csrf_token_generator: security.csrf.token_manager
                    use_referer: true
                provider: user_db_provider
                guard:
                    authenticators:
                        - form_authenticator
     
                # activate different ways to authenticate
     
                # http_basic: ~
                # http://symfony.com/doc/current/book/security.html#a-configuring-how-your-users-will-authenticate
     
                # form_login: ~
                # http://symfony.com/doc/current/cookbook/security/form_login_setup.html
        access_control:
            - { path: ^/login, roles: IS_AUTHENTICATED_ANONYMOUSLY }
            - { path: ^/register, role: IS_AUTHENTICATED_ANONYMOUSLY }
            - { path: ^/, roles: ROLE_USER }
            - { path: ^/admin, roles: ROLE_ADMIN }
    Le controller

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
     
     /**
         * @Route("/login", name="login")
         */
        public function loginAction(Request $request)
        {
     
            $user = $this->getUser();
     
            if ($user instanceof UserInterface) {
                return $this->redirectToRoute('homepage');
            }
     
            $authenticationUtils = $this->get('security.authentication_utils');
     
            $error = $authenticationUtils->getLastAuthenticationError();
            //j'ai bien le login et mdp du user
            var_dump($_POST);
            /**
             array (size=3)
                 '_username' => string 'jf' (length=2)
                 '_password' => string '123456' (length=5)
                 '_csrf_token' => string 'JO6q_GpqOkSzmHYy-L9HA9QDcnDmIor99va_E4w5ywo'
            */
     
            $lastUsername = $authenticationUtils->getLastUsername();
     
            return $this->render('security/login.html.twig', array(
                'last_username' => $lastUsername,
                'error' => $error,
            ));
     
        }
    et l'authenticator

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
     
    <?php
     
    namespace AppBundle\Security;
     
    use Symfony\Bridge\Doctrine\Security\User\EntityUserProvider;
    use Symfony\Component\HttpFoundation\RedirectResponse;
    use Symfony\Component\HttpFoundation\Request;
    use Symfony\Component\HttpFoundation\Response;
    use Symfony\Component\Routing\RouterInterface;
    use Symfony\Component\Security\Core\Exception\CustomUserMessageAuthenticationException;
    use Symfony\Component\Security\Core\Exception\UsernameNotFoundException;
    use Symfony\Component\Security\Core\Security;
    use Symfony\Component\Security\Core\User\UserInterface;
    use Symfony\Component\Security\Guard\AbstractGuardAuthenticator;
    use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
    use Symfony\Component\Security\Core\Exception\AuthenticationException;
    use Symfony\Component\Security\Core\User\UserProviderInterface;
     
    class FormAuthenticator extends AbstractGuardAuthenticator
    {
        /**
         * @var \Symfony\Component\Routing\RouterInterface
         */
        private $router;
        /**
         * Default message for authentication failure.
         *
         * @var string
         */
        private $failMessage = 'Invalid credentials';
     
        /**
         * Creates a new instance of FormAuthenticator
         */
        public function __construct(RouterInterface $router)
        {
            $this->router = $router;
        }
     
        /**
         * Returns a response that directs the user to authenticate.
         *
         * This is called when an anonymous request accesses a resource that
         * requires authentication. The job of this method is to return some
         * response that "helps" the user start into the authentication process.
         *
         * Examples:
         *  A) For a form login, you might redirect to the login page
         *      return new RedirectResponse('/login');
         *  B) For an API token authentication system, you return a 401 response
         *      return new Response('Auth header required', 401);
         *
         * @param Request $request The request that resulted in an AuthenticationException
         * @param AuthenticationException $authException The exception that started the authentication process
         *
         * @return Response
         */
        public function start(Request $request, AuthenticationException $authException = null)
        {
            $url = $this->router->generate('login');
            return new RedirectResponse($url);
        }
     
        /**
         * Get the authentication credentials from the request and return them
         * as any type (e.g. an associate array). If you return null, authentication
         * will be skipped.
         *
         * Whatever value you return here will be passed to getUser() and checkCredentials()
         *
         * For example, for a form login, you might:
         *
         *      if ($request->request->has('_username')) {
         *          return array(
         *              'username' => $request->request->get('_username'),
         *              'password' => $request->request->get('_password'),
         *          );
         *      } else {
         *          return;
         *      }
         *
         * Or for an API token that's on a header, you might use:
         *
         *      return array('api_key' => $request->headers->get('X-API-TOKEN'));
         *
         * @param Request $request
         *
         * @return mixed|null
         */
        public function getCredentials(Request $request)
        {
            var_dump("crede");
            exit();
            if ($request->getPathInfo() != '/login' || !$request->isMethod('POST')) {
                return;
            }
     
            if ($request->request->has('_username')) {
                return array(
                    'username' => $request->request->get('username'),
                    'password' => $request->request->get('password'),
                );
            }
            return;
        }
     
        /**
         * Return a UserInterface object based on the credentials.
         *
         * The *credentials* are the return value from getCredentials()
         *
         * You may throw an AuthenticationException if you wish. If you return
         * null, then a UsernameNotFoundException is thrown for you.
         *
         * @param mixed $credentials
         * @param UserProviderInterface $userProvider
         *
         * @throws AuthenticationException
         *
         * @return UserInterface|null
         */
        public function getUser($credentials, UserProviderInterface $userProvider)
        {
            var_dump("getuser");
            exit();
            if (!$userProvider instanceof EntityUserProvider) {
                return;
            }
            try {
                return $userProvider->loadUserByUsername($credentials['username']);
            } catch (UsernameNotFoundException $e) {
                throw new CustomUserMessageAuthenticationException($this->failMessage);
            }
        }
     
        /**
         * Returns true if the credentials are valid.
         *
         * If any value other than true is returned, authentication will
         * fail. You may also throw an AuthenticationException if you wish
         * to cause authentication to fail.
         *
         * The *credentials* are the return value from getCredentials()
         *
         * @param mixed $credentials
         * @param UserInterface $user
         *
         * @return bool
         *
         * @throws AuthenticationException
         */
        public function checkCredentials($credentials, UserInterface $user)
        {
            var_dump("check");
            exit();
            if ($user->getPassword() === $credentials['password']) {
                return true;
            }
            throw new CustomUserMessageAuthenticationException($this->failMessage);
        }
     
        /**
         * Called when authentication executed, but failed (e.g. wrong username password).
         *
         * This should return the Response sent back to the user, like a
         * RedirectResponse to the login page or a 403 response.
         *
         * If you return null, the request will continue, but the user will
         * not be authenticated. This is probably not what you want to do.
         *
         * @param Request $request
         * @param AuthenticationException $exception
         *
         * @return Response|null
         */
        public function onAuthenticationFailure(Request $request, AuthenticationException $exception)
        {
            var_dump("fail");
            exit();
            $request->getSession()->set(Security::AUTHENTICATION_ERROR, $exception);
            $url = $this->router->generate('login');
            return new RedirectResponse($url);
        }
     
        /**
         * Called when authentication executed and was successful!
         *
         * This should return the Response sent back to the user, like a
         * RedirectResponse to the last page they visited.
         *
         * If you return null, the current request will continue, and the user
         * will be authenticated. This makes sense, for example, with an API.
         *
         * @param Request $request
         * @param TokenInterface $token
         * @param string $providerKey The provider (i.e. firewall) key
         *
         * @return Response|null
         */
        public function onAuthenticationSuccess(Request $request, TokenInterface $token, $providerKey)
        {
            var_dump("success");
            exit();
            $url = $this->router->generate('homepage');
            return new RedirectResponse($url);
        }
     
        /**
         * Does this method support remember me cookies?
         *
         * Remember me cookie will be set if *all* of the following are met:
         *  A) This method returns true
         *  B) The remember_me key under your firewall is configured
         *  C) The "remember me" functionality is activated. This is usually
         *      done by having a _remember_me checkbox in your form, but
         *      can be configured by the "always_remember_me" and "remember_me_parameter"
         *      parameters under the "remember_me" firewall key
         *
         * @return bool
         */
        public function supportsRememberMe()
        {
            return false;
        }
    }

  2. #2
    Membre expert
    Avatar de dukoid
    Homme Profil pro
    Développeur informatique
    Inscrit en
    Novembre 2012
    Messages
    2 100
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations professionnelles :
    Activité : Développeur informatique

    Informations forums :
    Inscription : Novembre 2012
    Messages : 2 100
    Points : 3 004
    Points
    3 004
    Par défaut
    je ne sais pas si tu as configuré xdebug pour suivre le code pas à pas.

    sinon tu fais des dump(...); exit; par si par là en progressant dans le code pour voir ou ça bloque...

    comme tu as fais d'ailleurs, alors ça bloque ou ?

  3. #3
    Membre averti
    Homme Profil pro
    Développeur Web
    Inscrit en
    Février 2003
    Messages
    307
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 44
    Localisation : Belgique

    Informations professionnelles :
    Activité : Développeur Web
    Secteur : Administration - Collectivité locale

    Informations forums :
    Inscription : Février 2003
    Messages : 307
    Points : 378
    Points
    378
    Par défaut
    Oui c'est c'est que j'ai fait dans ma class FormAuthenticator

    mais à part la méthode start qui est appelé lorsqu'on accède à "/admin"
    les autres ne sont jamais appelées

    j'ai aussi mis un dump dans mon action et je reçois bien les données du formulaire

    je pense que c'est

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    $authenticationUtils = $this->get('security.authentication_utils');
    qui devrait réagir mais ne fait rien

  4. #4
    Membre expert
    Avatar de dukoid
    Homme Profil pro
    Développeur informatique
    Inscrit en
    Novembre 2012
    Messages
    2 100
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations professionnelles :
    Activité : Développeur informatique

    Informations forums :
    Inscription : Novembre 2012
    Messages : 2 100
    Points : 3 004
    Points
    3 004
    Par défaut
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
     
    $authenticationUtils = $this->get('security.authentication_utils');
    sauf erreur, ok tu récupères l'instance du service et donc ?

    tu en fais quoi ? tu appelles quelles méthodes ? etc...

  5. #5
    Membre averti
    Homme Profil pro
    Développeur Web
    Inscrit en
    Février 2003
    Messages
    307
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 44
    Localisation : Belgique

    Informations professionnelles :
    Activité : Développeur Web
    Secteur : Administration - Collectivité locale

    Informations forums :
    Inscription : Février 2003
    Messages : 307
    Points : 378
    Points
    378
    Par défaut
    Tout mon code se trouve dans le controller plus haut

    Comme il est indiqué ici :

    http://symfony.com/doc/current/secur...gin_setup.html

    Don't let this controller confuse you. As you'll see in a moment, when the user submits the form, the security system automatically handles the form submission for you.

    Ma méthode getCredentials de mon authenticator devrait appelé automatiquement

  6. #6
    Membre expert
    Avatar de dukoid
    Homme Profil pro
    Développeur informatique
    Inscrit en
    Novembre 2012
    Messages
    2 100
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations professionnelles :
    Activité : Développeur informatique

    Informations forums :
    Inscription : Novembre 2012
    Messages : 2 100
    Points : 3 004
    Points
    3 004
    Par défaut
    c'est la 1ere partie, qui sers à saisir le login et password
    http://symfony.com/doc/current/secur...gin_setup.html


    la 2eme partie : pour intégrer l'user en session ....
    http://symfony.com/doc/current/secur...ntication.html




    comme je l'ai dis plus haut,
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
     
    $authenticationUtils = $this->get('security.authentication_utils');
    ça fait rien, c'est une instance !

  7. #7
    Membre averti
    Homme Profil pro
    Développeur Web
    Inscrit en
    Février 2003
    Messages
    307
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 44
    Localisation : Belgique

    Informations professionnelles :
    Activité : Développeur Web
    Secteur : Administration - Collectivité locale

    Informations forums :
    Inscription : Février 2003
    Messages : 307
    Points : 378
    Points
    378
    Par défaut
    Si je remplace dans mon security.yml

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
     
    form_login:
        login_path: login
        check_path: login
        csrf_token_generator: security.csrf.token_manager
        use_referer: true
    par http_basic: ~

    mon authentification se fait bien il va voir dans la db user

    et pour mon loginAction, non il ne faut rien mettre d'autre que ce qu'il y a

    http://symfony.com/blog/new-in-symfo...t-improvements

    J'ai encore chercher pendant deux heures ce matin

  8. #8
    Membre averti
    Homme Profil pro
    Développeur Web
    Inscrit en
    Février 2003
    Messages
    307
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 44
    Localisation : Belgique

    Informations professionnelles :
    Activité : Développeur Web
    Secteur : Administration - Collectivité locale

    Informations forums :
    Inscription : Février 2003
    Messages : 307
    Points : 378
    Points
    378
    Par défaut
    Ouf j'ai enfin trouvé

    c'est à cause de ces lignes dans mon security.yml

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
     
    login_firewall:
                pattern:    ^/login$
                anonymous:  ~
    je les ai retiré et authentification se fait enfin

    Merci dukoid pour ton aide :-)

  9. #9
    Membre expert
    Avatar de dukoid
    Homme Profil pro
    Développeur informatique
    Inscrit en
    Novembre 2012
    Messages
    2 100
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations professionnelles :
    Activité : Développeur informatique

    Informations forums :
    Inscription : Novembre 2012
    Messages : 2 100
    Points : 3 004
    Points
    3 004
    Par défaut
    c'était le $ de pattern: ^/login$ qui posait problème ou toute la ligne ?


    parceque ce bout de code veut dire que les "anonymous" ont accès à /login , ce qui est logique...

+ Répondre à la discussion
Cette discussion est résolue.

Discussions similaires

  1. [VxiR2] Une ou 2 tables de faits dans mon univers ?
    Par Mafate dans le forum Designer
    Réponses: 2
    Dernier message: 23/03/2010, 09h31
  2. Réponses: 9
    Dernier message: 07/07/2008, 15h53
  3. Réponses: 1
    Dernier message: 10/02/2008, 20h31
  4. [Maven2] aucun artifact copié dans mon repo local
    Par jpalcluc dans le forum Maven
    Réponses: 4
    Dernier message: 17/07/2007, 17h12
  5. Réponses: 1
    Dernier message: 06/04/2005, 15h09

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo