Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
652 views
in Technique[技术] by (71.8m points)

authorization - Symfony - Throw an exception returning 403 from a Listener

I'm using Symfony5 with ApiPlatform

I'm using a Listener for multiple tasks including to do some authorization that I can't do in my voters.

So through a simple condition I verify what field of my entity is being modified.

I go through the modified fields, and check if they're different from the only field that can be modified.

here's how :

$modifiedValues = $eventArgs->getEntityManager()->getUnitOfWork()->getEntityChangeSet($eventArgs->getObject());

foreach ($modifiedValues as $key => $value) {
    if ("statut" != $key) {
        throw new AccessDeniedException('Vous ne pouvez pas modifier ce champ.');
    }    
}

Now I'm throwing an AccessDeniedException which I thought would return a 403 but actually return a 500.

The authorization part is actually working but I'm a bit bothered by this "exception" in my logic, cause other authorization rules will return either 200 or 403.

So my questions would be:

  • Does anyone know why this exception behave this way ? If it's normal behavior or something's off
  • Is there another way to return a 403 from this Listener ?

Thanks for your time!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

According to documentation you can configure the framework to catch your exception.

config/packages/api_platform.yaml

api_platform:
    exception_to_status:
        SymfonyComponentSecurityCoreExceptionAccessDeniedException: 403

But you should probably create your own Exception class, extend it from AcessDeniedException and configure it.

src/Exception/AccessDeniedException.php

<?php

namespace AppException;

use SymfonyComponentSecurityCoreExceptionAccessDeniedException;

class MyAccessDeniedException extends AccessDeniedException
{
}

config/packages/api_platform.yaml

api_platform:
    exception_to_status:
        AppExceptionMyAccessDeniedException: 403

Listener.php

$modifiedValues = $eventArgs->getEntityManager()->getUnitOfWork()->getEntityChangeSet($eventArgs->getObject());

foreach ($modifiedValues as $key => $value) {
    if ("statut" != $key) {
        throw new MyAccessDeniedException('Vous ne pouvez pas modifier ce champ.');
    }    
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...