Secure_Php_Restful_Webservice_using_middleware

Making restful web services secure

To make the php slim restful web services more secure we can use the technology called as middleware.

Middleware is used to check for cookies or headers present in request and validate them.

For example

 

or

 

Here before creating the employee using post method or updating existing employee using put method the “authenticateEmployee” routine well get called.

authenticateEmployee is method written in the index.php file inside api folder as follows. And we can also do role based authentication like.

For example Employee can update his own data using put call but can’t post new employee, while admin can do that.

Lets see the authenticateEmployee code.

 

Here in the above code the Xsrf (cross site request forging) token which is created once used is login in and stored inside session is checked if the xsrf token in session and in request is same or not if not then it return 401 http code that is unauthorised access.

Similar to the xsrf token the projectId and SomeKey is also checked from request and stored in session inside validateUserKey method as follows.

 

And if the the authenticateEmployee function which can be also treated as authenticateRole

returns 401 the further exception of restful get or post or any other method stops and http error code 401 will be returned.

Role based authentication to get response from a restful webserive.

Below code will reply if the user is Admin or Employer.

 

Below code will reply if the user is Admin.

 

Below code will reply if the user is Employee.

 

Updating the session time:

As the current user is logged in and the get, delete and post or other methods that is the restful requests are coming, we need to update the session timeout on server side accordingly.

So the below code is update the session time accordingly.

 

 

Download Code

Secure, role based php restful web service using json
Tagged on:                 

Leave a Reply

Your email address will not be published. Required fields are marked *