Understanding Authentication & Authorization (JWT, OAuth2.0, Session) Concepts
In this blog, I've shared my understanding on different Auth strategies. What is Authentication & Authorization? Authentication: The process of verifying the identity of a user or system. It ensures that the entity requesting access is who they claim to be. Common methods include passwords, biometrics, and tokens. Authorization: The process of determining what an authenticated user or system is allowed to do. It defines the permissions and access levels granted to the authenticated entity, such as reading, writing, or deleting resources. Auth Strategies Basic Authentication Most simplest form of authentication in which the client sends a Base64 encoded string in the Authorization Basic Header which is made from user credentials. An example would be, :, this is the format used and then encode this and attach it in the header. Eg: Field Value Credentials example@example.com:1234 Base64 encoded ZXhhbXBsZUBleGFtcGxlLmNvbToxMjM0 Header Authorization: Basic ZXhhbXBsZUBleGFtcGxlLmNvbToxMjM0 The server then receives the request, decodes the string, matches them against the database values and serves the response. Pros: Simple to use, can be used in services which don't require high level security. Cons: Doesn't provide extensive security, encoded string can be easily decrypted. JWT Authentication JWT or JSON Web Tokens are token-based strategy which allows parties to securely transmit information between themselves using JSON objects. The JWT is transferred in an encoded format which has 3 parts: Header Header contains the information about the cryptographic algorithm used and the type of token. eg: { "alg": "HS256", "typ": "JWT" } Payload A JSON object which contains the info the parties wanted to send between each other. Also known as Claims. There are some standard fields like "iat" (issued at), "exp" (expire at) etc, which are necessary for JWT validation and ensure security but are subject to your use case. eg: { "sub": "1234567890", "name": "John Doe", "admin": true, "iat": 1516239022 } Signature It's an encrypted string generated after applying the cryptographic algorithm in combination with the header, payload, and a secret key. A secret key is a private key known only to the server, used to sign the token and ensure its integrity. The signature ensures that the token has not been altered. If any part of the token changes, the signature will no longer match, and the token will be considered invalid. Eg. of a signature which uses SHA 256 algorithm: HMACSHA256( base64UrlEncode(header) + "." + base64UrlEncode(payload), secret) Eg. of a JWT: .. eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWUsImlhdCI6MTUxNjIzOTAyMn0.KMUFsIDTnFmyG3nMiGM6H9FNFUROf3wh7SmqJp-QV30 Verification and Validation of JWT: Verification involves checking the token's signature to ensure it was generated by the server and has not been tampered with. Validation involves checking the token's claims, such as expiration time, to ensure the token is still valid. How JWT auth flow works? Access Token: An access token is a short-lived token that is used to access protected resources. It is issued by the authentication server after the user successfully authenticates. The access token is included in the Authorization header of HTTP requests to the server. Access tokens have a limited lifespan and expire after a certain period, requiring the user to obtain a new token. Refresh Token: A refresh token is a long-lived token that is used to obtain a new access token without requiring the user to re-authenticate. The refresh token is issued along with the access token and is stored securely on the client side most likely in HTTP-Only secure cookie. When the access token expires, the client can use the refresh token to request a new access token from the authentication server. Refresh tokens also have an expiration time, but it is usually much longer than that of access tokens. Most auth systems store refresh tokens in a database to provide additional security and revoke capabilities if it gets stolen. JWT Auth Flow: The client sends a login request with user credentials to the authentication server. The server verifies the credentials and, if valid, issues an access token and a refresh token. The client stores the tokens securely and includes the access token in the Authorization header of subsequent requests to access protected resources. When the access token expires, the client uses the refresh token to request a new access token from the server. The server verifies the refresh token and, if valid, issues a new access token. The client continues to use the new access token to access protected resources. Pros: Stateless: JWTs are self-co

In this blog, I've shared my understanding on different Auth strategies.
What is Authentication & Authorization?
Authentication: The process of verifying the identity of a user or system. It ensures that the entity requesting access is who they claim to be. Common methods include passwords, biometrics, and tokens.
Authorization: The process of determining what an authenticated user or system is allowed to do. It defines the permissions and access levels granted to the authenticated entity, such as reading, writing, or deleting resources.
Auth Strategies
Basic Authentication
- Most simplest form of authentication in which the client sends a Base64 encoded string in the Authorization Basic Header which is made from user credentials.
- An example would be,
, this is the format used and then encode this and attach it in the header.: - Eg:
Field | Value |
---|---|
Credentials | example@example.com:1234 |
Base64 encoded | ZXhhbXBsZUBleGFtcGxlLmNvbToxMjM0 |
Header | Authorization: Basic ZXhhbXBsZUBleGFtcGxlLmNvbToxMjM0 |
- The server then receives the request, decodes the string, matches them against the database values and serves the response.
- Pros: Simple to use, can be used in services which don't require high level security.
- Cons: Doesn't provide extensive security, encoded string can be easily decrypted.
JWT Authentication
- JWT or JSON Web Tokens are token-based strategy which allows parties to securely transmit information between themselves using JSON objects.
The JWT is transferred in an encoded format which has 3 parts:
-
Header
- Header contains the information about the cryptographic algorithm used and the type of token.
- eg:
{
"alg": "HS256",
"typ": "JWT"
}
-
Payload
- A JSON object which contains the info the parties wanted to send between each other. Also known as Claims.
- There are some standard fields like "iat" (issued at), "exp" (expire at) etc, which are necessary for JWT validation and ensure security but are subject to your use case.
- eg:
{
"sub": "1234567890",
"name": "John Doe",
"admin": true,
"iat": 1516239022
}
-
Signature
- It's an encrypted string generated after applying the cryptographic algorithm in combination with the header, payload, and a secret key.
- A secret key is a private key known only to the server, used to sign the token and ensure its integrity.
- The signature ensures that the token has not been altered. If any part of the token changes, the signature will no longer match, and the token will be considered invalid.
- Eg. of a signature which uses
SHA 256
algorithm:
HMACSHA256(
base64UrlEncode(header) + "." +
base64UrlEncode(payload),
secret)
- Eg. of a JWT:
64Url-encoded header>. 64Url-encoded payload>. 64Url-encoded signature>
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWUsImlhdCI6MTUxNjIzOTAyMn0.KMUFsIDTnFmyG3nMiGM6H9FNFUROf3wh7SmqJp-QV30
-
Verification and Validation of JWT:
- Verification involves checking the token's signature to ensure it was generated by the server and has not been tampered with.
- Validation involves checking the token's claims, such as expiration time, to ensure the token is still valid.
- How JWT auth flow works?
-
Access Token:
- An access token is a short-lived token that is used to access protected resources. It is issued by the authentication server after the user successfully authenticates.
- The access token is included in the Authorization header of HTTP requests to the server.
- Access tokens have a limited lifespan and expire after a certain period, requiring the user to obtain a new token.
-
Refresh Token:
- A refresh token is a long-lived token that is used to obtain a new access token without requiring the user to re-authenticate.
- The refresh token is issued along with the access token and is stored securely on the client side most likely in HTTP-Only secure cookie.
- When the access token expires, the client can use the refresh token to request a new access token from the authentication server.
- Refresh tokens also have an expiration time, but it is usually much longer than that of access tokens.
- Most auth systems store refresh tokens in a database to provide additional security and revoke capabilities if it gets stolen.
-
JWT Auth Flow:
- The client sends a login request with user credentials to the authentication server.
- The server verifies the credentials and, if valid, issues an access token and a refresh token.
- The client stores the tokens securely and includes the access token in the Authorization header of subsequent requests to access protected resources.
- When the access token expires, the client uses the refresh token to request a new access token from the server.
- The server verifies the refresh token and, if valid, issues a new access token.
- The client continues to use the new access token to access protected resources.
-
Access Token:
-
Pros:
- Stateless: JWTs are self-contained and do not require server-side storage, making them ideal for distributed systems.
- Scalability: Since JWTs are stateless, they can be easily scaled across multiple servers without the need for session synchronization.
- Flexibility: JWTs can carry custom claims, allowing for flexible and extensible authentication mechanisms.
-
Cons:
- Token Size: JWTs can become large, especially when carrying many claims, which can impact performance.
- Security: If not properly secured, JWTs can be vulnerable to attacks such as token theft or tampering.
- A Practical implementation of JWT Authentication in
Golang
: https://github.com/the-arcade-01/golang-jwt-authentication
OAuth 2.0 Authorization
- OAuth 2.0 (Open Authorization) is an authorization strategy that allows third-party applications to access user resources without exposing user credentials.
- Example: Let's say in our app we want to access a user's photos which are stored in Google Drive. In this case, our app needs to access those photos on behalf of the user. To do that, we implement a mechanism using Google Auth provider, in which we specify to the user that we will only require permission to access the photos. Once the user grants us permission, we:
- Ask the Google Auth provider to generate an access token.
- Use the access token to access the Google photos.
Using this flow, we do not require the user to share their Google credentials and do not need to manage any additional information. Our app only needs client_id
& client_secret
for communicating with the Google Auth provider.
-
Pros:
- Security: OAuth 2.0 allows users to grant limited access to their resources without sharing their credentials, reducing the risk of credential theft.
- Granular Permissions: OAuth 2.0 supports fine-grained access control, allowing users to specify the exact permissions they want to grant to third-party applications.
- User Experience: OAuth 2.0 provides a seamless user experience by allowing users to authenticate using their existing accounts with trusted providers.
-
Cons:
- Complexity: Implementing OAuth 2.0 can be complex due to the various flows and security considerations involved.
- Token Management: Managing access and refresh tokens securely requires careful handling to prevent token theft and misuse.
- Dependency on Third-Party Providers: Relying on third-party authentication providers can introduce dependencies and potential points of failure.
A Practical implementation in
Golang
&React.js
:
https://github.com/the-arcade-01/react-golang-oauth-flow
Session-Based Authentication
- In Session-Based Authentication, a unique ID (known as "session ID") is generated on the server and is stored into a database after a successful login of the users. This identifier is then send backed to the user, and is stored in Cookies at the client side.
- How Session-Based auth flow works?
- User performs a login with its valid credentials.
- The server validates those credentials and then generates a unique ID, stores that into some database (eg: Redis) with an expiration time (TTL, Time To Live), and then sends it back to the user.
- The client then stores that session ID in the cookies and calls the subsequent requests using that ID.
- When server receives a request with the session ID, it fetches the session ID from database, checks whether it has not expired, then compares it with the request one, and if valid then proceed otherwise not.
- When user logs out then session ID is deleted. Plus system also use expiration time on Session ID so they get automatically deleted from the database.
Pros: Easier to implement, provides expiry control (is used redis then automatic expiry), session ID is stored in database which is secured.
Cons: Good for monolithic apps, for microservices, it requires centralized storage and service so the system is consistent like using API Gateway for all entry points and performing auth check.
Conclusion
Thanks for reading it and I hope I explain the concepts in an easy way. If you've any comments or want to give any suggestion, please leave it in the comments section.
Also I didn't cover RBAC (Role-Based Access Control) & ABAC (Attribute-Based Access Control) authorization methods because they are centric towards access control model. Although you can read about them here:
References
Some of the resources which I've used for writing this blog, these are some great resources which will help you understand things in more details.