Ultimate Magento 1 Developer Guide : Token Base Rest API for authentication and authorization

RestApi_TokenAuthentication

Security has always been a major concern we talk about high-level applications or mobile apps, especially when we talk about exposing our business through services. I have already explained a lot of REST API in my earlier articles. I explained, how do we create a Magento 1 REST API, how do we get the available categories from the store, How can you search the products in your mobile app etc. This article will explain how to make token based REST API to handle authentication among the devices. There is no standard way of doing token based authentication on the Magento 1 that’s why we design our own security technique and structure which suits best to our application.

One of the key principles of REST is that it’s stateless. This means that the server never keeps user state. In the context of security, this aspect has impacts when implementing security. This means that authentication hints must be sent and verified at each time.  An authenticated user will be allowed to access resources for a particular period of time and can re-instantiate the request with an increased session time delta to access other resource or the same resource.

Magento REST API Security

Magento 1 Security in itself is very complicated and tricky topic. I’ll try to explain how we can achieve it in REST API security in my own way. When we plan to create a mobile app, we especially want to take care of authentication and authorization. There are various ways to achieve security in Magento 1 but we have decided to use token-based authentication on our mobile app.

Authentication

Authentication is all about the identity of an end user. It’s about validating the identity of a user who is accessing our system, that he is authenticated enough to use our resources or not. Does that end user have valid credentials to log in our system? Credentials can be in the form of a username and password. We’ll use Basic Authentication technique to understand how we can achieve authentication in WebAPI.

Authorization

Authorization should be considered as a second step after authentication to achieve security. Authorization means what all permissions the authenticated user has to access web resources. Is allowed to access/ perform an action on that resource? This could be achieved by setting roles and permissions for an end user who is authenticated or can be achieved through providing a secure token, using which an end user can have access to other services or resources.

Magenot Token Based Authorization

Authorization part comes just after authentication, once authenticated a service can send a token to an end user through which user can access other resources. The token could be any encrypted key, which only server/service understands and when it fetches the token from the request made by the end user, it validates the token and authorizes user into the system. Token generated could be stored in a database or an external file as well i.e. we need to persist the token for future references. The token can have its own lifetime and may expire accordingly. In that case, the user will again have to be authenticated into the system.

Implementation of the token based authorization in Magento 1

Below is the code which we have used to create & manage tokens in Magento 1.x version.

 Public function generateUserToken($data){
        // get the username & password of the user
        $username = $data['username'];
    	$password = $data['password'];

        // check username password exists on our system or not
         if (!$customer->authenticate($username, $password)) {
              // user is not registered with this Magento 1 website
         }

        // load customer details if exist
	$customerObj = $customer->loadByEmail($username);
	$customerId =  $customerObj->getEntityId();

        // check user token is already generated or not and return token if exist and return the token from database if exist
	$customerapitokensObj = Mage::getModel('customerapi/customerapitokens');
	$customerapitokensObj->load($customerId, 'customer_id');
	if ($customerapitokensObj->getToken()){
		$token = $customerapitokensObj->getToken();
		return $token;
	}

        // generate token and save customer tokens
	try {
                // create MD5 token with username and password and date comibanation to make token unique
		$date  = date("Y-m-d H:i:s")."".$username."".$password;
		$token = md5(uniqid($date, true));
				
		$customerapitokensObj->setCustomerId($customerId);
		$customerapitokensObj->setToken($token);
		$customerapitokensObj->setStatus(1);
		$customerapitokensObj->setDate(date("Y-m-d H:i:s"));
		$newUserData = $customerapitokensObj->save();
				
		return $token; 
	} catch (Exception $e) {
		$this->_critical($e->getMessage(), Mage_Api2_Model_Server::HTTP_UNAUTHORIZED);
	}

}

Database Structure for the Token support

magentoTokenBasedAutentication

 

Conclusion

In this article, I tried to explain about how we can build an API application with basic Authentication and Authorization. One can mold this concept to achieve the level of security needed. If you want to implement Token-based-authentication on your Magento 1 mobile apps then you will find these above steps easier. The above code will create and manage the token-based authentication on your Magento 1 store and you can display on your mobile app. If any better approach or solution your thoughts are most welcome. Please share with us so that it might help others as well.

References

Further reading

 

Ultimate Magento 1 Developer Guide : Token Base Rest API for authentication and authorization was last modified: October 30th, 2017 by Javed Usmani