Symfony的安全返回401响应,而不是重定向
我在写与阿贾克斯验证Ajax应用程序,现在我开始用硅石symfony的安全组件来处理身份验证/授权。结果
做一个简单的测试用一个简单的配置,我去一个保护区由防火墙和我得到的回应是重定向到 /登录
页面,但我需要在我应用程序是可能的附加信息的401响应(页眉或JSON体)就如何登录。
I'm writing an ajax application with ajax authentication and now I started using the symfony security component in silex to handle authentication/authorization.
Doing a simple test with a simple configuration, I go to a protected area by the firewall and the response I get is a redirection to the /login
page but what I need in my app is a 401 response with possible additional information(in headers or json body) on how to login.
$app['security.firewalls'] = [
'api' => [
'pattern' => '^/api',
'logout' => ['logout_path'=>'/auth/logout'],
'users' => $app->share(function(Application $app) {
return new MyUserProvider();
})
]
];
编辑:我有一个暗示,但我不知道如何使用它。与实施 AuthenticationEntryPointInterface切入点
我可以告诉API如何回答未认证的请求,并给用户进行身份验证所需的指令。这可能是我的登录说明401响应。
I got a hint but I'm not sure how to use it. Implementing an entry point with AuthenticationEntryPointInterface
I can tell the api how to answer unauthenticated requests and give the user the instructions needed to authenticate. That could be my 401 response with login instructions.
您需要的是一个好的AuthenticationEntryPoint处理程序。
简单的例子:
What you need is a AuthenticationEntryPoint handler. Simple example:
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文件服务:
Register class as a service in services.xml file:
<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文件中一个小的变化:
and make a small change in security.yml file:
security:
firewalls:
somename:
entry_point: authentication_entry_point