开发者

PHP Symfony - Provide credentials only to owner of object

I am trying to wrap my head around symfony's user authentication. Need advice on best practices.

apps/frontend/modules/mymodule/config/security.yml

edit:
  is_secure: true
  credentials: owner

all:
  is_secure: false

When and where do I set $this->getUser()->addCredential('owner')? In a filter of the filter chain?

If I set it there, when do I remove the credentials again? I could just remove in the same filter, if the user is not the owner of that object, but then once the user edited one object, he will have the owner credentials, until he tries to edit something he doesn't own. Is there a drawback to that?

Or is there a way to set the needed credentials to the id of the object? Like

edit:
  is_secure: true
  credentials: %%request_id%%

And then add user credentials on login for all their ids?

Any insight would be much appreciated.


Update 1:

Would something like this work? Can't test right开发者_运维技巧 now if the code actually works. Would this be best practice?

apps/frontend/config/filters.yml

// ...

security:
  class: addOwnerCredentials

// ...

apps/frontend/lib/addOwnerCredentials.class.php

class addOwnerCredentials extends sfBasicSecurityFilter
{

  function execute($filterChain)
  {
    $context = $this->getContext();
    $request = $context->getRequest();
    $user = $context->getUser();

    $user_ids = $user->getAllOwnership();

    // Add owner credential for current user or remove if he has it but shouldn't
    if (in_array($request->getParameter('id'), $user_ids)) {
      $user->addCredential('owner');
    }
    elseif ($user->hasCredential('owner')) {
      $user->removeCredential('owner');
    }

    // Continue down normal filterChain
    parent::execute($filterChain);

    // On the way back, before rendering, remove owner credential again
    // The code after the call to $filterChain->execute() executes after the
    // action execution and before the rendering.
    if ($user->hasCredential('owner')) {
      $user->removeCredential('owner');
    }
  }

}

Update 2: Added to code snippet, to remove the owner credentials, right after they were needed, so the user doesn't have a unnecessary credential in their session.


I've put my custom filter which adds arbitrary credentials to user before security filter, not replaced them. This looks like only difference between our approaches :)

So, I'd say yes, it (I mean UPD1) is best practice.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜