Stateless authentication in Symfony 2

Everyone these days want’s an API. Mostly for some SPAs or for external applications. Common issue here is a security layer where you can’t use standard form and cookies. Other thing about state saved in cookies is f.ex. clickjacking. James Ward wrote about this some time ago.

So we have some requirements:

  • Authentication based on token
  • Token is send as part of each request to make API stateless
  • I want to be able to use Symfony Security layer as I do in “normal” applications
  • Bonus: I want authenticate each device with different token (when someone is using app on PC and phone in the same time)

So I went to Symfony Cookbook and I’ve found solution with my requirement in the title. And it wasn’t what I needed. OK, it’s about keys/tokens and probably I could make it working but I have a lot of free time during holidays so I can do better. So I went one article further to write my my own authentication provider. And there is of course article about it too.

Lets start with UserProvider. What I want is find User entity with given token and device identifier. Simple schema looks like this:

User and Identities

To find user I query by username when authenticating user by token and device on the beginning of each request and once in a while by username and password to create new Identity.

Interface like this is everything I need and it’s consistent with Liskov’s substitution principle (L in SOLID).

When I can find user all I need is follow Cookbook and everything is working great. SecureApiBundle is available on GitHub┬áso you can check how I’ve done this.

Update your composer.json file

enable it

and use secure-api in your security config:

I know it is possible to add paths for registration and session creation to config, but for now I don’t need this so I keep it simple :P Doctrine UserRepository is used here as User Provider with interface I mentioned earlier. Line 28 is marker that we are using our token solution for this firewall.

 

Handling multiple conditions OOP way

Many times in our applications we need to handle multiple conditions which most of the times ends as huge ifs. When we can do it fast & dirty it’s good enough but when we want to code clean we don’t really want huge procedural comparison. Continue reading “Handling multiple conditions OOP way”