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

Popular posts from this blog

javascript - Karma not able to start PhantomJS on Windows - Error: spawn UNKNOWN -

Nuget pack csproj using nuspec -

c# - Display ASPX Popup control in RowDeleteing Event (ASPX Gridview) -