Why do I get a "Unauthorized" error even though the user is logged-in? I am trying to programmatically log in a user in a custom module.

The code I am using in mymodule.module is the following.

function mymodule_form_alter(&amp;$form, $form_state, $form_id) {
  if ($form_id == 'user_login_block' || $form_id == 'user_login') {
    $form['#validate'] = array('user_login_name_validate', 'mymodule_login_validate', 'user_login_final_validate');
  }
}

function mymodule_login_validate($form, &amp;$form_state) {
  global $user;
  $username = $form_state['values']['name'];
  $password = $form_state['values']['pass'];

  $ch = curl_init();
  curl_setopt($ch,CURLOPT_URL, "http://localhost/MYAPI/oauth/authenticate"); 
  curl_setopt($ch, CURLOPT_POST, 1);
  curl_setopt($ch, CURLOPT_POSTFIELDS,"username=" . $username . "&amp;grant_type=password");
  curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/x-www-form-urlencoded", "Authorization:Basic xxxxxxxxxxxxxxx"));

  // receive server response ...
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  $server_output = curl_exec ($ch);
  curl_close ($ch);
  $postData = drupal_json_decode($server_output);
  $count = db_query("SELECT COUNT(*) FROM {users} WHERE name = :name;", array(':name' =&gt;$username))-&gt;fetchField();

  if ($count == 0) {
    if (!empty($postData['access_token'])) {
      $ch = curl_init();
      curl_setopt($ch, CURLOPT_URL,"http://localhost/MYAPI/rest/user/1/get_user_details");
      curl_setopt($ch, CURLOPT_POST, 1);
      curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/x-www-form-urlencoded", "Authorization:Bearer ".$postData['access_token']));

       // receive server response ...
       curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
       $server_output = curl_exec($ch);
       curl_close($ch);
       $postData = drupal_json_decode($server_output);
       $resRoleArr = $postData['userDetail']['role'];
       $resMail = $postData['userDetail']['email'];
       $roleArr = user_roles();
       $common_roles = array_intersect($resRoleArr,$roleArr);

       if (count($common_roles) &gt; 0) {
         user_external_login_register($username, 'mymodule');
         $user_fields = [
           'pass' =&gt; $password,
           'status' =&gt; 1,
           'mail' =&gt; $resMail,
           'init' =&gt; $resMail,
           'roles' =&gt; [DRUPAL_AUTHENTICATED_RID =&gt; 'authenticated user'],
         ];

         user_save((object) ['uid' =&gt; $user-&gt;uid], (array) $user_fields);
         $account = user_external_load($username);
         $form_state['uid'] = $account-&gt;uid;
         if ($role = user_role_load_by_name($common_roles)) {
           user_multiple_role_edit(array($user-&gt;uid), 'add_role', $role-&gt;rid);
         }
       }
     }
   }
   else {
     user_login_authenticate_validate($form,$form_state);
   }
 } 


As you can see I am trying to login an user externally where it's credentials coming from a REST API.

Before to externally log in, I check if the user already exists in the database.  if it doesn't exist, I use user_external_login_register($username, 'mymodule'); if it exists, I use    user_login_authenticate_validate($form,$form_state).

Though I am able to successfully log in the user in both the cases, I am getting an Unauthorized error.

What could the issue be?

I am using Drupal 7.56.
Below code might help you login-in with current user:

function mymodule_user_login_cred($username, $password)
{
  if(user_authenticate($username, $password))
  {
    $user_obj = user_load_by_name($username);
    $form_state = array();
    $form_state['uid'] = $user_obj-&gt;uid;      
    user_login_submit(array(), $form_state);
    return true;
  }
  else
  {
    return false;
  }
}