Access Tokens and the secrets around them .

omar gomaa
9 min readJul 15, 2023

--

Overview

After reading this article you will be able to :

1- Understand the main idea about Access Tokens .

2- Why it’s very useful and effective way to protect you APIs .

3- How end points in your API deal with Access Tokens and use them to connect with you “ with life example “.

4- JWT “ Json Web Token ” , its parts and purpose of it at Authentication and Authorization .

So , lets go …

Introduction

If you were trying to be a good frontend/mobile developer one day “ like me :) “ or you are already this person now , you could face and try to use any type of API on your project to get some data from external source and review them in your application .

Most of free limited APIs on the Internet you will try are un-secured , that means you don’t need to provide any information about you as a client want to access them . That because all information and data it provides is not much important or needs to be secured . It is only free dummy data for education and developing purposes .

One of these examples for free APIs you might try is JsonPlaceHolder API. One of the easiest and simplest end points you might try is GET Posts endpoint , and that the response of it when you make a request to it :

[
{
"userId": 1,
"id": 1,
"title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
"body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
},
{
"userId": 1,
"id": 2,
"title": "qui est esse",
"body": "est rerum tempore vitae\nsequi sint nihil reprehenderit dolor beatae ea dolores neque\nfugiat blanditiis voluptate porro vel nihil molestiae ut reiciendis\nqui aperiam non debitis possimus qui neque nisi nulla"
},
{
"userId": 1,
"id": 3,
"title": "ea molestias quasi exercitationem repellat qui ipsa sit aut",
"body": "et iusto sed quo iure\nvoluptatem occaecati omnis eligendi aut ad\nvoluptatem doloribus vel accusantium quis pariatur\nmolestiae porro eius odio et labore et velit aut"
},
{
"userId": 1,
"id": 4,
"title": "eum et est occaecati",
"body": "ullam et saepe reiciendis voluptatem adipisci\nsit amet autem assumenda provident rerum culpa\nquis hic commodi nesciunt rem tenetur doloremque ipsam iure\nquis sunt voluptatem rerum illo velit"
}
]

That’s very simple , you click request and the response loaded 200 OK successfully . But it won’t be so easy every time you will deal with it . If you try to go up with your level and try to practice on more advanced APIs , you will face an Authentication part on the API . Also if you work on complicated freelancing project or also at your company you have to deal with Authentication as a main part of your API .

Secured APIs

Dealing with that type of APIs and their end points needs little different approach than the free APIs . Secured or Authenticated APIs need from the users who want to access them some kind of Handshake or -trust exchange process- . Those APIs most of time allow you to access protected resources from Database . So , they need to know about their consumers . They don’t allow accessing their protected resources from anonymous people .

Free APIs VS Authenticated APIs

  • So , lets try to imagine a scenario of two developers , the first one try to access free API that allows anonymous accessing , and the second one try to access protected API.

Free API Accessing

Developer = Hey , I want to access your resources , and I am anonymous person ..

Api = Sure , you will get that …. !!

response : Json Object contains all data .

Secured API Accessing

Developer = Hey , I want to access your resources , and I am anonymous person ..

Api = No , only trusted ones could access the protected resources , I have to know who are you .. your user name .. your email .. and all your information to allow you accessing me . I am sorry !!

response : 401 Status Code “ Unauthorized ” ❌

Critical Thinking about solution

“ Ok I will provide my user name , email , and all needed information when I try to access any resources from any end point “

Hmm !! That’s effective way but not the optimal one , for more than one reason :

1- First, you need to provide all these information included : UserName , Email , Password , Address , Age … etc , every time you want to access any end point , that for me at least takes too much effort , and I think their are another lazy people accept that point of view with me .

2- Second, that’s doesn’t achieve any type of security , because any beginner Hacker can track the request from you to the server and steal all your personal info and use them to access all your protected resources and information from the server and … I will let you imagine the rest of the story 🤦‍♂️

Practical and Effective Solution

Let me provide the more effective and secure way to access your resources from the server .

“ it’s not 100% secure , but we try ”

1- First , you need to perform Register & Login Functionality as a Backend Developer for all users “Frontend & Mobile” .

2- Second , You will accept all needed information about user like : user name , email , address , age … etc . Then save them at your Authorization Server .

3- Third , and that the most tricky part and favorite to me , you will generate a link , an Id , also you could imagine that as Car License . That license contains and holds all your provided information and data in encrypted form . That what we called “ Access Token “ .

Access Token as Driver License

Access Token and its Usage

How can we use Access Tokens ??

Lets imagine this scenario , you buy a new beautiful car and one day you face an angry police man and he want to know and check that this car belongs to you and you ride it legally . You don’t need to give it all your information and you don’t need to show him all your papers and car’s paper . Only he will ask about your license card , and that card contains all information which he wants to know about you . If all data and information accept all roles , he will let you go , you will be happy .. the angry police man will be happy “ I guess “ ..

That the same idea of the Access Token .

But how access tokens hold all information of the logged in user and how all end points extract them ??

By the magic of the Encryption and Decryption . You provide all information and data in login/register end point , then the Backend Service will generate encrypted text by using Encryption Technologies with any type of encryption algorithm and that will be your Access Token

You should save that Token because you need it every time you want to access any resources or end points “ remember don’t forget your car license “ . The opposite operation of the Encryption , that called Decryption . You provide your access token “ license “ and it will be decrypted into understandable form contains all your data to test your credibility and security .

Let’s try the previous scenario I have mentioned from a while about the person who want to access Secured API :

Developer = Hey , I want to access your protected resources ..

Api = Who are you , I need your License ??

Developer = Sure , here my Token “ license “ that holds all my information .

Api = Ok , it is secured and you are trusted , you will get it

response : 200 OK Status Code 👍 ✔

JSON Web Token -JWT-

The most used type of Access Tokens in a lot of web apps and backend services is called JWT . It provides many types of Encryption Algorithms that allow you to have many options to ensure your security on your API by generating secure Access Token .

Generating JWT :

  • All you want is to make function that accepts all information you want to include at your personal token , then extract personal info , roles , claims , and any type of information you want to include in your login/register functionality .
  • Then the JWT will generate an unique , encrypted text/string specifically for you and for your information .

Example :

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9
.eyJzdWIiOiJvbWFyX2FkbWluQGV4YW1wbGUuY29tIiwianRpIjoiODdlMDlhYTUtMTM4OC00YzRmLTg2MzQtNDFmYjhhZThkZDc5IiwiZW1haWwiOiJvbWFyX2FkbWluQGV4YW1wbGUuY29tIiwidWlkIjoiOTQyZjJhYzctZmZmYS00Yzk3LTk1NTMtNGE3NTE1N2ZhNjI0Iiwicm9sZXMiOlsiQWRtaW4iLCJNYW5hZ2VyIl0sImV4cCI6MTY5MTcwNjk4MCwiaXNzIjoiU2VjdXJlQXBpIiwiYXVkIjoiU2VjdXJlQXBpVXNlciJ9
.c32Fn5YjM5z4stdoQsPNV-b0XoFzHuTcFyAa4JW7d9o

Parts of JWT

As you see I have put my JWT that I have generated during working on my Auth-WebApi Github Repo . Check that you will find small demo of using JWT with Identity Framework on .NET 6 Core API “ I am sure you will find that useful “ . JWT mainly has three parts.

JWT Parts

When you decrypt the JWT you will receive JSON Object that include some information . Depend on type of information we can part it to three parts . Every part is separated with other by dot “ . “ .

1- The First Part “ Header ” has JSON Object that holds the type of algorithm you used to encrypt your data and token type.

2- The Second Part “ Payload “ is the most important for us , that JSON Object includes all personal info of the user such as user name , email , user-id , expire-date of the token , roles of that user in your Database … etc .

3- The Last Part “ SIGNATURE “ that helps ensure that the data in the header and payload segments haven’t been tampered with, and the JWT can be trusted .

Decrypted information of the JWT Token I have mentioned :

HEADER:ALGORITHM & TOKEN TYPE : 
{
"alg": "HS256",
"typ": "JWT"
}
PAYLOAD:DATA
{
"sub": "omar_admin@example.com",
"jti": "87e09aa5-1388-4c4f-8634-41fb8ae8dd79",
"email": "omar_admin@example.com",
"uid": "942f2ac7-fffa-4c97-9553-4a75157fa624",
"roles": [
"Admin",
"Manager"
],
"exp": 1691706980,
"iss": "SecureApi",
"aud": "SecureApiUser"
}
VERIFY SIGNATURE
HMACSHA256(
base64UrlEncode(header) + "." +
base64UrlEncode(payload),

your-256-bit-secret
) secret base64 encoded

Access Tokens Secured 100 % ??

Unfortunately NO !!

Why ??

Imagine this scenario with me , while you sending multiple requests including your Access Token to use secured API , someone track your request and steal the data you send , included Access Token … !!

Now this person has your Token and can use and deal with your protected resources , and the API doesn’t have any problem and can’t reveal who the actual person who use this Access Token . That seems like a thief steal your license or your ID and use it to get access to any place you are registered on by that ID .

Don’t be afraid , Fortunately there is another technique make your APIs go to the next level of security and make the stolen Token by the thief useless and has no value with him .

What is that and how we can use it ?? That’s what we called Refresh Token . We will talk about this concept in another article with more details . 😉

Summery

  • You should secure your APIs that deal with protected resources by using both Authentication & Authorization .
  • The most used and effective way of saving and secure your APIs is using Access Tokens .
  • Access Token is a link between you and the server to communicate with each other and to prove you’re secured person to access resources .
  • Access Token can be defined as Car License that holds all your personal information to make you secured person for server “ Police “ .
  • JWT is the most used way of using and generating Access Tokens for web APIs .
  • JWT has main three parts : Header , Payload & Signature .
  • JWT by itself is not secure 100 % , but we use another token called Refresh Token to make your API more secure .

See you soon ..

--

--