title: Implementing an RESTful API Authentication using tokens (Yii/Yii2)
body: <p>I am building an API in Yii 1.x which will be used with a mobile application. Part of the process involves a login (with a username and password) using the following JSON request below:-</p>
  
  <p>// Request sent with username &amp; password</p>
  
  <pre><code>{
  "request" : {
      "model" : {
          "username" : "bobbysmith",
          "password" : "mystrongpassword"
      }
    }
  }
  </code></pre>
  
  <p>// If successfully logged in return the following response</p>
  
  <pre><code>{
  "response": {
      "code": 200,
      "message": "OK",
      "model": {
          "timestamp": 1408109484,
          "token": "633uq4t0qdtd1mdllnv2h1vs32"
      }
   }
  }
  </code></pre>
  
  <p>This token is quite important - once a user is logged in on the app I'd like them to have access to other pages that require them to be logged in. I want the mobile app to store this token &amp; if the same <strong>633uq4t0qdtd1mdllnv2h1vs32</strong> token is found within any subsequent requests it will accept this as being an authenticated request (for this user 'bobbysmith').</p>
  
  <p>I am a little unsure of how to best go about doing this, I have done some research and can oAuth has been mentioned a few times, along with Basic Authentication via HTTPS.</p>
  
  <p>So in a nutshell this...</p>
  
  <ol>
  <li>On mobile app homepage, user logs in correctly with their username &amp; password &amp; this sends a request to the API.</li>
  <li>This returns a successful response (shown above) with the current timestamp &amp; the all important token.</li>
  <li>The same user goes to another app page/view where this token is a) required and b) if it matches up this authenticates that user (e.g so they can edit that account etc..)</li>
  <li>Once user clicks 'Logout' this token is then removed (and can longer access My Account etc..) - essentially a token based authentication system.</li>
  </ol>
  
  <p>Can anyone possibly explain the best way to achieve this? Please let me know if what I have stated isn't 100% clear and i'll provide more information.</p>
  
  <p>While I am using PHP, a Yii 1.x solution is ideal as that is what the current API is built using.</p>
  
  <p>In a nutshell, the app ensures that every request to server includes token in the payload or header so this token can be retrieved on <strong>every</strong> subsequent post, once logged out this token is simply removed OR set to null/empty</p>