API Security in Action epub cover
welcome to this free extract from
an online version of the Manning book.
to read more
or

4 Session cookie authentication

 

This chapter covers

  • Building a simple web-based client and UI
  • Implementing token-based authentication
  • Using session cookies in an API
  • Preventing cross-site request forgery attacks

So far, you have required API clients to submit a username and password on every API request to enforce authentication. While simple, this approach has several downsides from both a security and usability point of view. In this chapter, you’ll learn about those downsides and implement an alternative known as token-based authentication, where the username and password are supplied once to a dedicated login endpoint. A time-limited token is then issued to the client that can be used in place of the user’s credentials for subsequent API calls. You will extend the Natter API with a login endpoint and simple session cookies and learn how to protect those against cross-site request forgery (CSRF) and other attacks. The focus of this chapter is authentication of web-based clients hosted on the same site as the API. Chapter 5 covers techniques for clients on other domains and non-browser clients.

Definition

In token-based authentication, a user’s real credentials are presented once, and the client is then given a short-lived token. A token is typically a short random string that can be used to authenticate API calls until the token expires.

4.1       Authentication in web browsers

4.1.1   Calling the Natter API from JavaScript

4.1.2   Intercepting form submission

4.1.3   Serving the HTML from the same origin

4.1.4   Drawbacks of HTTP authentication

4.2       Token-based authentication

4.2.1   A token store abstraction

4.2.2   Implementing token-based login

4.3       Session cookies

4.3.1   Avoiding session fixation attacks

4.3.2   Cookie security attributes

4.3.3   Validating session cookies

4.4       Preventing cross-site request forgery attacks

4.4.1   SameSite cookies

4.4.2   Hash-based double-submit cookies

4.4.3   Double-submit cookies for the Natter API

4.5       Building the Natter login UI

4.5.1   Calling the login API from JavaScript

4.6       Implementing logout

4.7       Summary

sitemap