http basic authentication - How to configure http_basic firewall in Symfony to return JSON in response body? -
by default, when configure http_basic
firewall in symfony, firewall return "401 unauthorized
" , empty body requests fail.
i'd have return custom json (eg: {success: false, error: 401}
). possible?
here's configuration:
security: firewalls: api: http_basic: provider: myprovider
you need use custom authenticationentrypoint
. create class implementing 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; } }
the class needs accessible service add services.yml
. pass realm argument.
custom_basic_authentication_entry_point: class: appbundle\custombasicauthenticationentrypoint arguments: [ main ]
you can use in security.yml
:
firewalls: main: anonymous: ~ http_basic: ~ entry_point: custom_basic_authentication_entry_point
Comments
Post a Comment