title: Secure API for both mobile and web
body: <p>I have three applications:</p>
  <ul>
  <li>REST API</li>
  <li>Single Page Web App</li>
  <li>Native Mobile App.</li>
  </ul>
  <p>Both the web app and the mobile app uses the API for user authentication and fetching user specific data.</p>
  <p>My problem is then how to secure this API against CSRF, XSS and other types of attacks.</p>
  <p>As I understand, there are two common authentication strategies that each has pros and cons:</p>
  <ul>
  <li>Token based authentication</li>
  <li>Session/cookie based authentication (secured and httponly)</li>
  </ul>
  <h2>Session/cookie based authentication</h2>
  <p>Cookies are vulnerable to CSRF attacks, so to protect against that i would need to implement CSRF tokens, or a similar protection strategy. For a secure CSRF token implementation I should also setup proper CORS policy, so foreign sites can't get a CSRF token from the API. This is also good and well for the web app, however not possible for the mobile app, as mobile apps doesn't support CORS (it has now domain or origin header).</p>
  <h2>Token based authentication</h2>
  <p>The alternative is token based authentication, which works well for mobile apps, and removes the need for CSRF tokens as they themselves validates the
  authenticity of the request. However there are no secure way to store tokens in a Single Page Web App (locale/web storage is not secure, and if I use cookies, we are basically back to our first problems).</p>
  <h2>Problem</h2>
  <p>So my problem is, how should i implement secure authentication for both apps?</p>
  <p>My current idea would be to implement both strategies but only allow token auth when origin is not present, and only allow session/cookie auth when origin header is present and allowed by the CORS policy.</p>
  <p>But I'm in no way an expert on the subject, and might easily have misunderstood something. Any suggestions or further explanations would be very welcome :)!</p>