php - Symfony 安全返回 401 响应而不是重定向

标签 php security authentication symfony silex

我正在编写一个带有 ajax 身份验证的 ajax 应用程序,现在我开始使用 silex 中的 symfony 安全组件来处理身份验证/授权。
使用简单配置进行简单测试,我通过防火墙进入 protected 区域,得到的响应是重定向到 /login 页面,但我的应用程序需要的是 401 响应关于如何登录的可能的附加信息(在标题或 json 正文中)。

$app['security.firewalls'] = [
    'api' => [
        'pattern' => '^/api',
        'logout' => ['logout_path'=>'/auth/logout'],
        'users' => $app->share(function(Application $app) {
            return new MyUserProvider();
        })
    ]
];

编辑: 我得到了提示,但我不确定如何使用它。使用 AuthenticationEntryPointInterface 实现入口点我可以告诉 api 如何回答未经身份验证的请求并为用户提供身份验证所需的说明。这可能是我带有登录说明的 401 响应。

最佳答案

您需要的是 AuthenticationEntryPoint 处理程序。 简单示例:

class AuthenticationEntryPoint implements AuthenticationEntryPointInterface {

/**
 * Starts the authentication scheme.
 *
 * @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)
{
    $array = array('success' => false);
    $response = new Response(json_encode($array), 401);
    $response->headers->set('Content-Type', 'application/json');

    return $response;
}
}

在 services.xml 文件中将类注册为服务:

<parameters>
    <parameter key="authentication_entry_point.class">YourNameSpace\AuthenticationEntryPoint</parameter>
</parameters>

<services>
    <service id="authentication_entry_point" class="%authentication_entry_point.class%"/>
</services>

并对 security.yml 文件做一点小改动:

security:
  firewalls:
    somename:
      entry_point: authentication_entry_point

关于php - Symfony 安全返回 401 响应而不是重定向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18662579/

相关文章:

php - 如何使用 php 从 mysql 中的表中获取多行...

php - 为什么 in_array 不适用于在 PHP 中使用循环创建的数组?

java - 安全存储用户名和密码

php - 将 CURLOPT_SSL_VERIFYPEER 设置为 FALSE 是否安全?即使你控制两个服务器?

asp.net-mvc - ASP.NET MVC 3 连接以保护远程 WCF 服务

security - OAuth 和 SSO 功能

php - 用 openssl_crypt 替换 mcrypt

php - 在PHP中打印 boolean 值

php - 没有 CSRF token 的表单 : what are the risks

javascript - 根据用户状态显示/隐藏登录/注销按钮