首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

如何在Symfony中用FOSUserBundle制作多个登录表单

在Symfony中使用FOSUserBundle制作多个登录表单需要一些额外的步骤。以下是一个详细的指南,帮助你实现这一目标。

1. 安装和配置FOSUserBundle

首先,确保你已经安装并配置了FOSUserBundle。如果还没有安装,可以按照官方文档进行安装:

代码语言:javascript
复制
composer require friendsofsymfony/user-bundle "~2.0"

然后在 app/AppKernel.php 中注册bundle:

代码语言:javascript
复制
public function registerBundles()
{
    $bundles = [
        // ...
        new FOS\UserBundle\FOSUserBundle(),
    ];
}

app/config/config.yml 中配置FOSUserBundle:

代码语言:javascript
复制
fos_user:
    db_driver: orm
    firewall_name: main
    user_class: AppBundle\Entity\User

2. 创建多个防火墙

为了支持多个登录表单,你需要为每个表单创建一个独立的防火墙。在 app/config/security.yml 中添加多个防火墙:

代码语言:javascript
复制
security:
    firewalls:
        main:
            pattern: ^/
            form_login:
                provider: fos_userbundle
                csrf_token_generator: security.csrf.token_manager
                login_path: fos_user_security_login
                check_path: fos_user_security_check
            logout:
                path: fos_user_security_logout
                target: homepage
            anonymous: true

        admin:
            pattern: ^/admin
            form_login:
                provider: fos_userbundle
                csrf_token_generator: security.csrf.token_manager
                login_path: fos_user_admin_login
                check_path: fos_user_admin_check
            logout:
                path: fos_user_admin_logout
                target: /admin
            anonymous: false

3. 创建自定义登录控制器

为每个防火墙创建自定义的登录控制器。例如,为 admin 防火墙创建一个控制器:

代码语言:javascript
复制
php bin/console generate:controller Admin

在生成的控制器中添加登录方法:

代码语言:javascript
复制
namespace AppBundle\Controller\Admin;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Core\Security;

class AdminController extends Controller
{
    public function loginAction(Request $request)
    {
        $authenticationUtils = $this->get('security.authentication_utils');

        // get the login error if there is one
        $error = $authenticationUtils->getLastAuthenticationError();

        // last username entered by the user
        $lastUsername = $authenticationUtils->getLastUsername();

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

4. 创建登录模板

为每个登录表单创建相应的Twig模板。例如,为 admin 登录表单创建 admin/login.html.twig

代码语言:javascript
复制
{% extends "base.html.twig" %}

{% block body %}
    <h2>Admin Login</h2>
    {% if error %}
        <div>{{ error.messageKey|trans(error.messageData, 'security') }}</div>
    {% endif %}

    <form action="{{ path('fos_user_admin_check') }}" method="post">
        <input type="hidden" name="_csrf_token" value="{{ csrf_token('authenticate') }}">

        <label for="username">Username:</label>
        <input type="text" id="username" name="_username" value="{{ last_username }}" required="required" autofocus="autofocus"/>

        <label for="password">Password:</label>
        <input type="password" id="password" name="_password" required="required"/>

        <button type="submit">Login</button>
    </form>
{% endblock %}

5. 更新路由

确保你的路由配置中包含了新的登录路径。在 app/config/routing.yml 中添加:

代码语言:javascript
复制
fos_user_security:
    resource: "@FOSUserBundle/Resources/config/routing/security.xml"

fos_user_admin:
    resource: "@AppBundle/Controller/Admin"
    type:     annotation
    prefix:   /admin

然后在 AppBundle/Controller/Admin 目录下创建 AdminController.php 并添加路由注解:

代码语言:javascript
复制
/**
 * @Route("/admin")
 */
class AdminController extends Controller
{
    /**
     * @Route("/login", name="fos_user_admin_login")
     */
    public function loginAction()
    {
        // ...
    }

    /**
     * @Route("/login_check", name="fos_user_admin_check")
     */
    public function checkAction()
    {
        throw new \RuntimeException('You must configure the check path to be handled by the firewall using form_login in your security firewall configuration.');
    }

    /**
     * @Route("/logout", name="fos_user_admin_logout")
     */
    public function logoutAction()
    {
        throw new \RuntimeException('You must configure the logout path to be handled by the firewall using form_login in your security firewall configuration.');
    }
}

6. 测试

现在你可以启动你的Symfony应用并测试多个登录表单是否正常工作。访问 /admin/login 应该会显示 admin 防火墙的登录表单,而默认的 /login 路径应该显示 main 防火墙的登录表单。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

领券