0
0
Rest APIprogramming~30 mins

Token refresh mechanism in Rest API - Mini Project: Build & Apply

Choose your learning style9 modes available
Token Refresh Mechanism
📖 Scenario: You are building a simple REST API that uses tokens to allow users to access protected resources. Tokens expire after some time, so you need a way to refresh them without asking the user to log in again.
🎯 Goal: Create a token refresh mechanism that checks if the current token is expired and issues a new token if needed.
📋 What You'll Learn
Create a dictionary called tokens with user tokens and their expiry times
Create a variable called current_time representing the current time
Write a function called refresh_token that takes a user and refreshes the token if expired
Print the refreshed token or a message if the token is still valid
💡 Why This Matters
🌍 Real World
Token refresh mechanisms are used in apps and websites to keep users logged in securely without asking for passwords repeatedly.
💼 Career
Understanding token refresh is important for backend developers working on authentication and security in web services.
Progress0 / 4 steps
1
Create the initial tokens dictionary
Create a dictionary called tokens with these exact entries: 'alice': {'token': 'abc123', 'expiry': 100}, 'bob': {'token': 'def456', 'expiry': 200}, and 'carol': {'token': 'ghi789', 'expiry': 50}.
Rest API
Need a hint?

Use a dictionary with usernames as keys and another dictionary as values holding 'token' and 'expiry'.

2
Set the current time
Create a variable called current_time and set it to 120 to represent the current time.
Rest API
Need a hint?

Just assign the number 120 to the variable current_time.

3
Write the token refresh function
Write a function called refresh_token that takes a parameter user. Inside the function, check if tokens[user]['expiry'] is less than current_time. If yes, update tokens[user]['token'] to 'newtoken123' and tokens[user]['expiry'] to current_time + 100. Otherwise, do nothing.
Rest API
Need a hint?

Use an if statement to compare expiry with current_time and update the token and expiry if expired.

4
Print the refreshed token
Call refresh_token for the user 'alice'. Then print the string "Refreshed token for alice: " followed by tokens['alice']['token'].
Rest API
Need a hint?

Call the function with 'alice' and print the message with the updated token.