API Auth Approaches

Anurag Jain
2 min readJan 1, 2023

Http Basic Auth

We pass a username and password in a request, encoded using base64. This method can be used for internal server-side APIs.

Session/Cookie

When a client sends a login request, the server creates a session for that user and sends a "set-cookie" header in the response. The browser then stores the cookie and includes it in every subsequent request to the server.

  • This approach requires distributed cache to store the session for scaling.
  • This method is suitable for web-based applications as browsers are designed to handle cookies, but it can be challenging to implement for mobile and server-side applications.
  • This approach is vulnerable to CSRF attacks, so we need to implement prevention mechanisms. Many frameworks, such as Django, include built-in CSRF prevention.

Random Token

To verify login, the client makes an API call to the server. Upon successful login, the server generates a token and associates it with the user’s username. The token is then returned to the client, who includes it in the authorization header as necessary. This approach can be used by any type of client, including web, mobile, and server. When using this approach, it’s important to have a distributed cache in place to handle session scaling.

JWT Token

The token is generated using a shared secret or public-private key and contains information about the user.

  • The client sends the token back to the server, which can then use a key to decode it. If the token has been tampered with or has expired, the decoding process will fail and the server will reject the token. If the token is valid and not expired, the server can extract the user information from the decoded token.
  • Typically, this token has a short expiration time, so the client must use a refresh token to obtain a new token.

Why refresh token required in JWT ?

  • Revoking Token is not possible if you want to achieve stateless solution else you have to implement distributed db for looking up the revoked tokens.

OpenID Connect

it helps in building “Signin using <…>” functionality.

Oauth

When a third-party application wants to access your application on behalf of a user, an access token is provided by the resource server, such as Google, after the user grants permission. Then the third-party application can use this access token to directly call the resource server’s APIs. An example of this would be when your application wants to access a particular user’s contacts.

--

--