symfony - 如何在 Symfony 中配置 http_basic 防火墙以在响应正文中返回 JSON?

标签 symfony basic-authentication

默认情况下,当您在 Symfony 中配置 http_basic 防火墙时,防火墙将返回“401 Unauthorized”,并为失败的请求返回一个空正文。

我想让它返回自定义 JSON(例如:{success: false, error: 401})。这可能吗?

这是我的配置:

security:
    firewalls:
        api:
            http_basic:
                provider: myprovider

最佳答案

您需要使用自定义AuthenticationEntryPoint。创建一个实现 AuthenticationEntryPointInterface 的类:

<?php

namespace AppBundle;

use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Http\EntryPoint\AuthenticationEntryPointInterface;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;

class CustomBasicAuthenticationEntryPoint implements AuthenticationEntryPointInterface {

    private $realmName;

    public function __construct($realmName) {
        $this->realmName = $realmName;
    }

    public function start(Request $request, AuthenticationException $authException = null) {
        $content = array('success' => false, 'error' => 401);

        $response = new Response();
        $response->headers->set('WWW-Authenticate', sprintf('Basic realm="%s"', $this->realmName));
        $response->headers->set('Content-Type', 'application/json');
        $response->setContent(json_encode($content))
                ->setStatusCode(401);
        return $response;
    }    
}

该类需要作为服务进行访问,因此将其添加到 services.yml 中。将领域作为参数传递。

custom_basic_authentication_entry_point:
         class: AppBundle\CustomBasicAuthenticationEntryPoint
         arguments: [ main ]

然后您可以在 security.yml 中使用它:

firewalls:
       main:
            anonymous: ~
            http_basic: ~
            entry_point: custom_basic_authentication_entry_point

关于symfony - 如何在 Symfony 中配置 http_basic 防火墙以在响应正文中返回 JSON?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31589601/

相关文章:

PHP curl : Max Length on CURLOPT_USERPWD?

powershell - 使用 Invoke-WebRequest 以及用户名和密码在 GitHub API 上进行基本身份验证

symfony - 在symfony2中通过IMAP检索邮件的正确方法

Symfony - ManyToOne 关系中的循环引用错误

templates - 如何动态获取当前 Twig 模板的路径?

python - CherryPy webapp 的基本身份验证

ruby-on-rails - Rails HTTP 基本身份验证失败

configuration - Symfony2 树生成器 - 方法 canBeUnset() 做什么?

symfony - KnpMenuBundle 不适用于 Bootstrap 4 导航栏

javascript - Firefox 4 中的基本身份验证未注销