How to Setup a SecurityServiceProvider with Custom REST API and Success/Failure Handlers?-Collection of common programming errors
I have an AngularJS front end being served via domain.com/index.html. My API calls are all in the same domain scope at domain.com/api/*. I want to enable standard username/password authentication. However, all I need the Silex back end to do is set the session up and return a 200 success or 401 failure status codes at login time. I found pieces of code from the silex, symfony2 docs as SO but just can’t get it quite right. I basically setup my custom Success/Failure custom handlers to return the codes and apply them to the firewall. My “check_path” in the firewall/form settings seems to be the only real peace that’s important.
And here is most of the code. Hope it’s formatted well enough for you to help. Thanks!
app.php
// Setup sessions
$app->register(new Silex\Provider\SessionServiceProvider());
// General Service Provder for Controllers
$app->register(new Silex\Provider\ServiceControllerServiceProvider());
$app['security.authentication.success_handler.auth'] = $app->share(function ($app) {
return new ChrDb\Security\AuthSuccessHandler();
});
$app['security.authentication.failure_handler.auth'] = $app->share(function ($app) {
return new ChrDb\Security\AuthFailureHandler();
});
// Define a custom encoder for Security/Authentication
$app['security.encoder.digest'] = $app->share(function ($app) {
// uses the password-compat encryption
return new BCryptPasswordEncoder(10);
});
// Security definition.
$app->register(new SecurityServiceProvider(), array(
'security.firewalls' => array(
// Login URL is open to everybody.
// 'login' => array(
// 'pattern' => '^/api/login$',
// 'anonymous' => true,
// ),
// Any other URL requires auth.
'auth' => array(
//'pattern' => '^.*$',
'pattern' => '^/api$',
'form' => array(
'login_path' => '/api/auth/login',
'check_path' => '/api/login',
'username_parameter' => 'username',
'password_parameter' => 'password'
),
'logout' => array('logout_path' => '/api/auth/logout'),
'users' => $app->share(function() use ($app) {
return new ChrDb\Security\UserProvider($app);
}),
),
),
));
$app['api.auth.controller'] = $app->share(function() use ($app) {
return new ChrDb\Api\AuthController();
});
$app->get('/api/auth/login', "api.auth.controller:loginAction");
$app->get('/api/auth/logout', "api.auth.controller:logoutAction");
Here is the rest of the relevant code:
Originally posted 2013-11-27 11:51:53.