11 API authorization and authentication

 

This chapter covers

  • Using Open Authorization to allow access to our APIs
  • Using OpenID Connect to verify the identity of our API users
  • What kinds of authorization flows exist, and which flow is more suitable for each authorization scenario
  • Understanding JSON Web Tokens (JWT) and using Python’s PyJWT library to produce and validate them
  • Adding authentication and authorization middleware to our APIs

In 2018, a weakness in the API authentication system of the US postal system (https://usps.com) allowed hackers to obtain data from 60 million users, including their email addresses, phone numbers, and other personal details.1 API security attacks like this have become more and more common, with an estimated growth of over 300% in the number of attacks in 2021.2 API vulnerabilities don’t only risk exposing sensitive data from your users; they can also put you out of business!3 The good news is there are steps you can take to reduce the risk of an API breach. The first line of defense is a robust authentication and authorization system. In this chapter, you’ll learn to prevent unauthorized access to your APIs by using standard authentication and authorization protocols.

11.1 Setting up the environment for this chapter

11.2 Understanding authentication and authorization protocols

11.2.1 Understanding Open Authorization

11.2.2 Understanding OpenID Connect

11.3 Working with JSON Web Tokens

11.3.1 Understanding the JWT header

11.3.2 Understanding JWT claims

11.3.3 Producing JWTs

11.3.4 Inspecting JWTs

11.3.5 Validating JWTs

11.4 Adding authorization to the API server

11.4.1 Creating an authorization module

11.4.2 Creating an authorization middleware

11.4.3 Adding CORS middleware

11.5 Authorizing resource access