This content originally appeared on Level Up Coding - Medium and was authored by Lye Jia Jun
Table of Content
- Background/Problem Statement
- What is JWT (JSON Web Token)?
- How and When Are JSON Web Tokens Used?
- How does OAuth 2.0 work?
- The Role of JWT Access Token in OAuth 2.0
- The Inner Workings of JSON Web Token
- Some Final Tips & Actionable Takeaways
Background/Problem Statement
Creating your custom login flow is difficult
Sometimes risky too. To design a secure and lightweight login procedure, you need to have a deep understanding of cybersecurity principles and good software design knowledge.
This proves to be rather challenging for both small and large companies alike — what if you fail to properly encrypt sensitive information? What if your password hash is easily exploitable?
Delegation to Identity Providers
To avoid these complications, we delegate such tasks to identity providers and use the commonly seen ‘Sign In with Google’ or ‘Sign In with Facebook’ authentication methods.
While working with such authentication methods, you may often see terms such as OAuth 2.0 and JWT.
But what exactly is OAuth 2.0 and how does it relate to JWT?
In this article, I’ll be sharing everything you’ll need to know about OAuth 2.0 and JWT. If you’re a software architect, software engineer, or just a passionate techie, you should definitely read on to learn more!
What is JWT (JSON Web Token)?
In the simplest term, JWT — also known as JSON Web Token — is a standard for securely transmitting information between different parties through a JSON object.
The information transmitted via JWT can also be verified as it is digitally signed. Digitally signed information allows us to ensure that the information we received is not tampered with, thus ensuring the integrity of the information.
Also, if you’re curious, this is what a JSON Web Token looks like in its compact form.
How and When Are JSON Web Tokens Used?
Typically, you’ll see JWT being used in multiple authentication/authorization scenarios.
For instance, when you integrate Google Sign-In on your website, you’d likely follow the OAuth (Open Authorization) 2.0 standard and receive a JWT Access Token at the end of the transaction.
The JWT Access Token is then used to authorize the client app to access protected resources.
How does OAuth 2.0 work?
To understand JWT better, we need to first understand OAuth 2.0.
Here is a TLDR; version of OAuth 2.0 explanation. I will be focusing only on the core concepts of OAuth 2.0, just enough for you to understand the role of JWTs in OAuth 2.0.
In this explanation, let us use an example of a developer who is building a finance app that needs to interface with the bank‘s server.
In this example, our finance app needs to access our user’s (i.e. John) banking information to display a financial dashboard for our user to track his finances.
There are 4 roles in OAuth 2.0
- Resource Owner: the user that owns the protected resources, i.e. John
- Client: the system that needs access to the protected resources, i.e. our finance app
- Authorization Server: a server that handles the authorization process so that your client (finance app) can access the protected resources, i.e. the bank’s authorization server
- Resource Server: a server that receives access requests and returns the protected resources, i.e. the bank’s resource server
*The protected resources in the example below refer to John’s banking information.
The General OAuth 2.0 Workflow
This is the OAuth 2.0 workflow for our finance app to access our user’s banking information.
The workflow may look complicated but it is actually very logical if you try to read and comprehend it slowly.
- The finance app (client) requests authorization from the bank’s authorization server by supplying the client ID and client secret as identification.
- The bank’s authorization server authenticates the finance app (client) based on the supplied credentials and verifies that the request is permitted by asking John (the resource owner) if he consents to let the finance app (client) access his protected bank resources.
- John (the resource owner) authorizes the finance app (client) access to his protected bank resources.
- The bank’s authorization server then returns back the finance app (client) with a JWT access token.
- The finance app (client) can now request protected resources from the bank’s resource server using the JWT access token.
- The bank’s resource server, upon recognizing a valid JWT access token, returns the protected resources on request.
Note* the workflow above can also be extended with Google’s Authorization Server if the bank decides to use Google as an identity provider.
The Role of JWT Access Token in OAuth 2.0
To put it simply, the JWT access token here plays the role of proving that the user making the request to extract the protected resources is indeed authorized to access it.
JWT access token is an authorization mechanism.
The Inner Workings of JSON Web Token
Recall that JWT (JSON Web Token) is a standard for securely transmitting information between different parties through a JSON object.
But why is the JWT standard used in OAuth 2.0? Why can’t OAuth 2.0 simply use an encrypted string for authentication? How does JSON Web Token really work? To find our answers to these questions, let us explore the inner workings of JSON Web Token.
JWT Common Usecases
Firstly, remember that the JSON Web Token is most commonly used for authorization purposes. Also, because of its design, it can also be used for information exchange as JWTs are digitally signed. Thus you can verify that the message content hasn’t been tampered with.
JSON Web Token Structure
In its compact form, a JSON Web Token looks like this.
There are 3 parts to a JSON Web Token — Header, Payload, and Signature. Each part is separated by a period/dot.
Here, the header is in red text, the payload is in purple text, and the signature is in blue text.
Header — First Part of Token
The header of a JWT Token is simply a JSON data that contains 2 pieces of information — the type of token, and the signing algorithm used (i.e. HMAC SHA256)
Example:
{
"alg": "HS256",
"typ": "JWT"
}
This JSON data will then be Base64Url encoded to form the first part of the JWT.
Base64Url encoded output: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9
Note*
- Base64Url encoding refers to converting binary data (i.e. 101101) into ASCII string format.
- Spacing matters. If you try to paste the well-formatted JSON data above into a Base64Url encoder, you’ll get this output ewogICJhbGciOiAiSFMyNTYiLAogICJ0eXAiOiAiSldUIgp9 . The JSON data I used to base64url encode is {“alg”:”HS256",”typ”:”JWT”}
Payload — Second Part of Token
The payload contains data about an entity (typically, the user).
Example:
{
"sub": "1234567890",
"name": "John Doe",
"iat": 1516239022
}
Again, the JSON data is Base64Url encoded to form the second part of the JWT.
Signature — Third/Last Part of Token
The final part of our JSON Web Token — the signature — is more complicated, but extremely critical.
The signature requires 4 inputs
- The base64Url encoded Header JSON data (i.e. eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9)
- The base64Url encoded Payload JSON data (i.e. eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ)
- A secret string/key (i.e. secret)
- The signing algorithm specified in the Header JSON data (i.e. HMAC SHA256)
With the 4 inputs, the signature is created with the following algorithm:
HMACSHA256(
base64UrlEncode(header) + "." +
base64UrlEncode(payload),
secret
)
and the HMAC SHA256 output would be XbPfbIHMI6arZ3Y922BhjWgQzWXcXNrz0ogtVhfEd2o
Note* — The signature ensures the integrity of the message. If the secret here is signed with a private key, we can also ensure authentication and non-repudiation.
The JSON Web Token — combining all 3 parts (header, payload, and signature)
Header: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9
Payload: eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ
Signature: XbPfbIHMI6arZ3Y922BhjWgQzWXcXNrz0ogtVhfEd2o
Some Final Tips & Actionable Takeaways
If you managed to make it here, congratulations! You now understand the fundamental concepts of JSON Web Token and how it is used in standards such as OAuth 2.0.
Before you leave, I would like to share some valuable actionable takeaways and tips on your interaction with JWT when you use them for future projects.
- Do NOT store sensitive data in JWT payload. The payload is base64url encoded, NOT encrypted. Attackers can run a simple base64url decode to extract the payload content.
- DO store JWT in httpOnly cookies. Since many will need JWT for their user to make authorized requests to the backend, you need to store the JWT somewhere. The most secure place to store JWTs is in httpOnly cookies.
- DO use a strong secret for your JWT signature. If you name your secret as your application/company name, you’re asking to be exploited! A good rule of thumb is the longer the length of the secret, the better.
And… that’s it!
Just like how most cybersecurity professionals can’t escape coding, most developers also cannot escape the need for understanding core security principles.
I am grateful for having a cybersecurity academic background with rich software engineering experience, which allows me to marry my skills in both domains.
However, you don’t have to study cybersecurity for 3 years to learn all the essential knowledge to become a great software engineer/architect! Just continue what you’re doing — reading one article at a time, implementing one technical concept at a time — and you’ll be golden!
If you want to accelerate your way to becoming more technical and skilled in the software domain, do drop me a follow! Cheers!
Resources
- https://jwt.io/introduction
- https://jwt.io/#debugger-io
- https://auth0.com/intro-to-iam/what-is-oauth-2/
- https://auth0.com/docs/secure/tokens/access-tokens
Level Up Coding
Thanks for being a part of our community! More content in the Level Up Coding publication.
Follow: Twitter, LinkedIn, Newsletter
Level Up is transforming tech recruiting 👉 Join our talent collective
What the heck are JWT and OAuth 2.0? was originally published in Level Up Coding on Medium, where people are continuing the conversation by highlighting and responding to this story.
This content originally appeared on Level Up Coding - Medium and was authored by Lye Jia Jun
Lye Jia Jun | Sciencx (2022-07-14T02:17:56+00:00) What the heck are JWT and OAuth 2.0?. Retrieved from https://www.scien.cx/2022/07/14/what-the-heck-are-jwt-and-oauth-2-0/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.