0

I try to use to add the RequestAuthorizationMiddleware for some controller in my application in cake 4. In the Authorization Middleware i see a code block like this:

$middlewareQueue->add(new AuthorizationMiddleware($this, [
    'unauthorizedHandler' => [
        'className' => 'Authorization.Redirect',
        'url' => '/users/login',
        'queryParam' => 'redirectUrl',
        'exceptions' => [
            MissingIdentityException::class,
            OtherException::class,
        ],
    ],
]));

I can add a redirect url if the authorization failed. This work fine but how i can add a redirect url for the Request Authorization Middleware ?

ndm
  • 59,784
  • 9
  • 71
  • 110
wiifree
  • 55
  • 1
  • 7

1 Answers1

3

You don't really get a redirect with that when authorization fails, but when authorization cannot be performed to begin with, that is when no authenticated identity is present that could be used for authorizing, that will throw the following exception:

\Authorization\Exception\MissingIdentityException

If you want to catch unsuccessful authorization, ie when the user/identity isn't allowed to access whatever resource you're protecting, then you need to handle the following exception too:

\Authorization\Exception\ForbiddenException

That exception is thrown by the request authorization middleware, as well as by the authorization component (unless you're doing manual can* checks).

Just add it to the exceptions config and you should be good to go (that is assuming you are OK with redirects happening for all failed authorization attempts that aren't handled by manual can* checks):

'exceptions' => [
    \Authorization\Exception\MissingIdentityException::class,
    \Authorization\Exception\ForbiddenException::class,
    // ...
],

Note that in order for all this to work properly, you have to add the request authorization middleware after the default authorization middleware!

ndm
  • 59,784
  • 9
  • 71
  • 110