title: Authentication with AngularJS, session management and security issues with REST Api WS
body: <p>I started developing a web-app with angularJS and I'm not sure that everything is right secured (client and server side). 
  Security is based on a single login page, if credentials are checked ok, my server sends back an unique token with custom time-validity. All other REST api are accessible through this token.
  The application (client) browse to my entry-point ex: <a href="https://www.example.com/home.html">https://www.example.com/home.html</a> user insert credentials and receive back a unique token. This unique token is stored in the server database with AES or other secure techniques, it is not stored in clear format.</p>
  
  <p>From now on, my AngluarJS app will use this token to authenticate to all REST Api exposed.</p>
  
  <p>I'm thinking on temporary store the token in a custom http cookie; basically, when the server verifies the credentials, it sends back a new cookie Ex. </p>
  
  <pre><code>app-token : AIXOLQRYIlWTXOLQRYI3XOLQXOLQRYIRYIFD0T
  </code></pre>
  
  <p>The cookie has the <a href="https://www.owasp.org/index.php/SecureFlag">secure</a> and <a href="https://www.owasp.org/index.php/HttpOnly">HTTP Only</a> flags set on.
  Http protocol directly manage the new cookie and store it. Successive requests will presents the cookie with the new parameter, without the need to manage it and store it with javascript; at every request, server invalidates the token and generates a new one and sends it back to the client --> prevent replay-attacks with a single token.</p>
  
  <p>When the client receives an HTTP status <em>401 unauthorized</em> response from any REST Api, the angular controller clean all the cookies and redirect the user to the login page.</p>
  
  <p>Should I have to consider other aspects? Is it better to store the token inside a new cookie or in localStorage? 
  Any tips on how to generate a unique strong token?</p>
  
  <p><strong>Edit (improvements):</strong></p>
  
  <ul>
  <li>I decided to use HMAC-SHA256 as session token generator, with 20 minutes validity. I generate a random 32byte GUID, attach a timestamp and compute the HASH-SHA256 by providing a 40 bytes key. It's quite impossible to obtain collisions since the token validity is quite minimal.</li>
  <li>Cookie will have <a href="https://www.owasp.org/index.php/Session_Management_Cheat_Sheet#Domain_and_Path_Attributes">domain and path</a> attributes to increase security.</li>
  <li>No multi-logins are permitted.</li>
  </ul>