Magento REST without oAuth (custom REST authentication adapter)

By default Magento uses oAuth for REST API. In some cases oAuth is not needed, and the client wants to make REST calls without additional overhead (for example, mobile application that interacts with Magento store). Fortunately, Magento provides an easy way to achieve this.

Securing REST calls

Of course, we need to keep our calls secure. This can be done using hash-based message authentication code (HMAC)

The main idea here – that we use secret key for signing requests.

  1. We send the data (e.g. in JSON format), and we send signature header (hash based on the secret key and the data itself).
  2. Server receives the request, calculates the hash and compares it to the signature value (from request headers). If hashes are equal, then we can trust this client and we can proceed with the client’s call.

Custom authentication adapter for REST API

This adapter is intended to work with “customer” user type (there is no sense to use it with “guest” user type, and for “admin” user type you can implement your own adapter).

Prerequisites: Let’s assume that we have the module named Snowcore_Hmac and we have some API methods already implemented for the customer user type. Also, we have configured properly REST Roles and Attributes.

The client is supposed to send us hash value in Signature header (HMAC can be calculated on any platform: Android, iOS etc.)

 

New customer attribute

At first, we need to create a new customer attribute for storing secret key, let’s name it rest_hmac_secret_key. I am omitting this step, basically, you need to create installer/upgrade script and add varchar attribute for the customer entity.

Adapter declaration

It is possible to add custom authentication adapter using config.xml. So, let’s declare the adapter in the global section in our extension:

By default, Magento has just only one REST authentication adapter – oAuth (see Mage_Api2_Model_Auth_Adapter_Oauth class).

All the checks are performed in Mage_Api2_Model_Auth_Adapter::getUserParams() method.

I have set the order value to 5 for our adapter, so it will be executed before oAuth adapter.

And here is the code of the adapter itself:

In getUserParams() method we are loading the customers collection and checking hashes for every customer (you can add your own logic for retrieving customers, for example using some custom attribute such as “Has HMAC access”).

HMAC hash can be calculated easily and quickly using hash_hmac function in php.

That’s it. If you have any questions – feel free to post a comment. Thank you!

  • kiran

    Hi Can we get the complete module for above implementation.

    • Snowcore

      The actual module is project-specific with it’s own dependencies, so it will be not possible to use it.