Thursday, September 1, 2016

Authorization and Event Sourcing with prooph and ZF2 / ZF3

Authorization with prooph components and event sourced aggregates roots are a common problem to solve. Here is a short explanation on how to do this using Zend\Authentication. First of all, we need an aggregate root class for it. Here is a minimal example with some basic properties. Additionally, we will need a read only version of the aggregate root: And a projector, too: This is a very simple example, omitting the event classes and value objects. It might be worth adding some additional methods and/ or properties, when needed. The login command simply takes the email address and password as parameters, that's simple enough for us now, so what's needed is a command handler for Login / Logout. That should be enough for now. We also need an implementation of Zend\Authentication\Storage\StorageInterface. In this case, we use MongoDB as backend. Next we need an implementation of Zend\Authentication\Adapter\ValidatableAdapterInterface: Now we need two little factories to create our infrastructure: and this one: Last thing we need to do, is configure the service manager accordingly: So when I did not forget anything, that's it! With the last 3 lines of service manager config, you can even use prooph's ServiceBus ZFC-RBAC-bridge

2 comments:

  1. If you want your `Identity` aggregate to be testable you could change your `login` function to also take a `PasswordInterface` interface as a second argument.
    In your tests you would then have an implementation of the `PasswordInterface` whose `create` method would simply return the password and the verify method checks that the password and hash are equivalent.
    This would require that your `ZendMongoDbAuthAdapter` (and other adapters?) has a reference to a `PasswordInterface` but that's easily solved using your container.

    ReplyDelete
    Replies
    1. Yes for sure. I just wanted to hold this sample implementation as simple as possible.

      Delete