为API配置防火墙

时间:2019-11-03 21:54:42

标签: symfony symfony4

我正在尝试使用身份验证系统开发API。 但是我的默认路由/的响应始终显示Symfony默认欢迎页面的源代码,而不是没有找到路由或不需要身份验证。我的配置有什么问题。

我的security.yaml文件

security:
    encoders:
        App\Entity\User:
            algorithm: auto

    providers:
        app_user_provider:
            entity:
                class: App\Entity\User
                property: email

    firewalls:
        dev:
            pattern: ^/(_(profiler|wdt)|css|images|js)/
            security: false
        main:
            pattern: ^/
            anonymous: true
            json_login:
                check_path: /api/login
            logout:
                path: /api/logout
                success_handler: api.logout.success.listener

    access_control:
        - { path: ^/, roles: IS_AUTHENTICATED_FULLY }

我的SecurityController

/**
 * @Route("/api")
 */
class SecurityController extends AbstractController
{
    /**
     * @Route("/", name="api", methods={"GET"})
     * @param Request $request
     * @return JsonResponse
     */
    public function test(Request $request)
    {
        return $this->json([
            'message' => 'test'
        ]);
    }

    /**
     * @Route("/login", name="login", methods={"POST"})
     * @param Request $request
     * @return JsonResponse
     */
    public function login(Request $request)
    {
        $user = $this->getUser();

        return $this->json([
            'username' => $user->getUsername(),
            'roles' => $user->getRoles(),
        ]);
    }

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

1 个答案:

答案 0 :(得分:0)

问题解决了,我终于添加了一个带有默认路由“ /”的DefaultController,该路由抛出NotFoundException。