What happens if we want to use a security layer? We can use sessions. Sessions are the “standard” way to perform authentication in web applications, but when our application is a PhoneGap/Cordova application that uses a Silex server as API server, sessions aren’t the best way. The best way now is a token based authentication. The idea is simple. First we need a valid token. Our API server will give us a valid token if we send valid credentials in a login form. Then we need to send the token with each request (the same way than we send the session cookie with each request).

It isn’t an elegant solution. We need to validate the token within all routes and that’s bored. We also can use middlewares and validates the token with $app->before(). We’re going to build something like this, but with a few variations. First I want to keep the main application as clean as possible. Validation logic must be separated from application logic, so we will extend Silex\Application. Our main application will be like this:

Our new G\Silex\Application is a Silex\Application enabling CORS. We also mount a Service provider.

The responsibility of our API server will be check the token of every request and to provide one way to get a new token. To get a new token we will create a route “/auth/validateCredentials”. If a valid credentials are given, new token will be send to client.

As we can see the logic of the example is very simple. It’s just an example and here we must to perform our logic. Probably we need to check credentials with our database, and our token must be stored somewhere to be validated later.

You can see the example in my github account. In another post we will see how to build a client application with angularJs to use this API server.

This is great information – I’ve looked for a solid Token tutorial for a bit and found this understandable and helpful. I’m not familiar with Silex but will look more but just one quick question – what authenticates the credentials – that is if I put in a login and password – where is looking to authenticate those values? What are the correct values for your example? Thanks for the help.

private function getNewTokenForUser($user)
Creates a new token for a validated user. Here the token is always ‘a’, but you’ll need to create a unique token for the user and store it within a persistent storage

private function validateToken($token)
Validates token against the persistent storage. In this example toke is always ‘a’. Because of that the validation is very simple.