首页 > 解决方案 > Symfony - 当我去 /login 时总是退出

问题描述

我的问题很简单,我从今天早上就开始了。

当我去 /login 时,我直接断开连接,我在 symfony 5 上切换到匿名状态。

这是我的登录控制器:

/**
 * @Route("/login", name="app_login")
 * @param AuthenticationUtils $authenticationUtils
 * @return Response
 */
public function login(AuthenticationUtils $authenticationUtils): Response
{
     if ($this->getUser()) {
         return $this->redirectToRoute('index');
     }

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

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

在我进入我的状态之前(如果.. this->getUser()),我已经断开了连接。

这是我的注销控制器:

/**
 * @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');
}

和 security.yaml :

security:
encoders:
    App\Entity\User:
        algorithm: bcrypt
# https://symfony.com/doc/current/security.html#where-do-users-come-from-user-providers
providers:
    users_in_memory: { memory: null }
    app_user_provider:
        entity:
            class: App\Entity\User
            property: email
firewalls:
    dev:
        pattern: ^/(_(profiler|wdt)|css|images|js)/
        security: false
    main:
        anonymous: lazy
        provider: users_in_memory
        guard:
            authenticators:
                - App\Security\SecureAuthentication
        logout:
            path: app_logout
            # where to redirect after logout
            target: index

        # activate different ways to authenticate
        # https://symfony.com/doc/current/security.html#firewalls-authentication

        # https://symfony.com/doc/current/security/impersonating_user.html
        # switch_user: true

# Easy way to control access for large sections of your site
# Note: Only the *first* access control that matches will be used
access_control:
    # - { path: ^/admin, roles: ROLE_ADMIN }
    # - { path: ^/profile, roles: ROLE_USER }

非常感谢,祝你有美好的一天

标签: phpsymfonyauthenticationsymfony4

解决方案


在您设置的主防火墙配置中

    main:
        provider: users_in_memory

因此,您正在使用没有用户的提供程序,因此您应该无法登录。尝试将其更改为app_user_provider.

此外,您的主防火墙上缺少一个模式。我从来没有没有模式的防火墙配置,所以我不确定在这种情况下会发生什么。它有可能只是跳过它。

    main:
        pattern: ^/

你可以尝试这两件事,但一定要一一做才能知道哪一个解决了问题(如果这确实是解决方案):)


推荐阅读