title: Handling authentication for JSON API requests in CakePHP REST plugin
body: <p>I have being attempting to build an API for my CakePHP app using the REST plugin here: <a href="https://github.com/kvz/cakephp-rest-plugin" rel="nofollow noreferrer">https://github.com/kvz/cakephp-rest-plugin</a></p>
  
  <p>The reason for using this plugin is because I wanted an easy way to handle authentication with regards to API calls on protected methods and also deal with logging etc in the the future.</p>
  
  <p>In order to prevent duplication, the plugin is setup as described in a previous question: <a href="https://stackoverflow.com/questions/14288331/cakephp-rest-plugin-not-returning-data">CakePHP REST Plugin not returning data</a> which has now been fixed and works.</p>
  
  <p>The next part is handling authentication. I have added the following to my beforeFilter method which basically should be saying if it's a rest call and the user ins't logged in (note: that not all methods require a user to be logged in) then log them in.</p>
  
  <pre><code>if (!$this-&gt;Auth-&gt;user()) {
  
              if ($this-&gt;Rest-&gt;isActive()) {   
  
                  $loginUser = $this-&gt;User-&gt;loginUser(
                      $credentials['username'],
                      AuthComponent::password($credentials['password'])
                  );
  
                  if($loginUser) {                        
                      if (!$this-&gt;Auth-&gt;login($loginUser['User'])) {
                          $msg = sprintf('Unable to log you in with the supplied credentials. ');
                          return $this-&gt;Rest-&gt;abort(array('status' =&gt; '403', 'error' =&gt; $msg));
                      }
                  }
  
              }
          }
  </code></pre>
  
  <p>and for those that want to see the model call:</p>
  
  <pre><code> public function loginUser($usernameOrEmail, $password)
      {
          return $this-&gt;find('first', array(
              'conditions' =&gt; array(
                  'OR' =&gt; array(
                      'User.email' =&gt; $usernameOrEmail,
                      'User.username' =&gt; $usernameOrEmail,
                      'User.phone' =&gt; $usernameOrEmail
                  ),
                  'User.password' =&gt; $password
              ),
              'recursive' =&gt; -1
          ));
      }
  </code></pre>
  
  <p>However I can't get it to work. I'm doing the request like so for testing:</p>
  
  <pre><code>    $.ajax({
          url: 'http://domain.com/users/test.json',
          dataType: 'jsonp',
          data: { username: 'test', password: 'test' },
          headers: {
              Authorization: "TRUEREST"
          },
          success: function(response) {
              console.log(resonse);
          },
          error: function(jqXHR, textStatus, errorThrown) {
              console.log(jqXHR, textStatus, errorThrown);
          }
      });
  </code></pre>
  
  <p>The three main questions I have here are:</p>
  
  <ul>
  <li><p>I'm manually passing the username and password here BUT is the headers part correct? The explanation regarding it is rather vague on the documentation for this here: <a href="https://github.com/kvz/cakephp-rest-plugin#authorization" rel="nofollow noreferrer">https://github.com/kvz/cakephp-rest-plugin#authorization</a></p></li>
  <li><p>Is <code>$credentials['username']</code> going to pick it up? Is $credentials a global thing with HTTP authentication or have I missed something?</p></li>
  <li><p>Is this going to log the user in every time they make a request? As it seems a little messy if that's the case. </p></li>
  </ul>
  
  <p>The current code implementation errors with: <code>Uncaught SyntaxError: Unexpected token :</code></p>
  
  <p>and here is the JSON output which looks fine to me...</p>
  
  <pre><code>{
      "data": {
          "User": []
      },
      "meta": {
          "status": "error",
          "feedback": [{
              "message": "Log in to continue",
              "level": "error"
          }],
          "request": {
              "http_host": "domain.com",
              "http_user_agent": "Mozilla\/5.0 (Macintosh; Intel Mac OS X 10_8_2) AppleWebKit\/537.22 (KHTML, like Gecko) Chrome\/25.0.1364.29 Safari\/537.22",
              "server_addr": "##.##.###.###",
              "remote_addr": "##.###.###.###",
              "server_protocol": "HTTP\/1.1",
              "request_method": "GET",
              "request_uri": "\/users\/test.json?callback=jQuery172015279368730261922_1358207116601&amp;username=test&amp;password=test123&amp;_=1358207116611",
              "request_time": 1358207116
          },
          "credentials": {
              "class": null,
              "apikey": null,
              "username": null
          },
          "time_epoch": "1358207117",
          "time_local": "Mon, 14 Jan 2013 15:45:17 -0800",
          "version": "0.3"
      }
  }
  </code></pre>