Skip to content

Commit a17965e

Browse files
nykopolxabbuh
authored andcommitted
add documentation about access denied handler
1 parent a994b72 commit a17965e

File tree

2 files changed

+69
-0
lines changed

2 files changed

+69
-0
lines changed

security.rst

+1
Original file line numberDiff line numberDiff line change
@@ -1320,6 +1320,7 @@ Authorization (Denying Access)
13201320
security/force_https
13211321
security/securing_services
13221322
security/access_control
1323+
security/access_denied_handler
13231324

13241325
Other Security Related Topics
13251326
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

security/access_denied_handler.rst

+68
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
.. index::
2+
single: Security; Creating a Custom Access Denied Handler
3+
4+
How to Create a Custom Access Denied Handler
5+
============================================
6+
7+
When your application throw an ``AccessDeniedException`` you can catch this exception
8+
with a service to return a custom Response.
9+
10+
On each firewall context you can define a custom access denied handler.
11+
12+
.. configuration-block::
13+
14+
.. code-block:: yaml
15+
16+
# app/config/security.yml
17+
firewalls:
18+
foo:
19+
# ...
20+
access_denied_handler: custom_handler.service.id
21+
22+
.. code-block:: php
23+
24+
// app/config/security.php
25+
$container->loadFromExtension('security', array(
26+
'firewalls' => array(
27+
'foo' => array(
28+
// ...
29+
'access_denied_handler' => 'custom_handler.service.id',
30+
),
31+
),
32+
));
33+
34+
35+
Your handler must implement the interface
36+
:class:`Symfony\\Component\\Security\\Http\\Authorization\\AccessDeniedHandlerInterface`.
37+
This interface define one method called ``handle()`` that can do whatever you want.
38+
You can use it to send a mail, log a message, or generally return a custom Response.
39+
40+
41+
.. code-block:: php
42+
43+
namespace AppBundle\Security;
44+
45+
use Symfony\Component\Security\Http\Authorization\AccessDeniedHandlerInterface;
46+
use Symfony\Component\HttpFoundation\Request;
47+
use Symfony\Component\HttpFoundation\Response;
48+
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
49+
50+
class AccessDeniedHandler implements AccessDeniedHandlerInterface
51+
{
52+
public function handle(Request $request, AccessDeniedException $accessDeniedException)
53+
{
54+
// to some stuff...
55+
return new Response($content, 403);
56+
}
57+
}
58+
59+
Then you must register your service :
60+
61+
.. code-block:: yml
62+
63+
# app/config/services.yml
64+
services:
65+
custom_handler.service.id:
66+
class: AppBundle\Security\AccessDeniedHandler
67+
68+
That's it, now on the ``foo`` firewall, all ``AccessDeniedException`` will be notified to you service.

0 commit comments

Comments
 (0)