Bird
Raised Fist0
Rest APIprogramming~20 mins

Token refresh mechanism in Rest API - Practice Problems & Coding Challenges

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Challenge - 5 Problems
🎖️
Token Refresh Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
What is the output of this token refresh simulation?
Consider a simple token refresh function that returns a new access token if the refresh token is valid. What will be the output of the code below?
Rest API
def refresh_token(refresh_token):
    valid_refresh_tokens = {"abc123": "new_access_token_1", "def456": "new_access_token_2"}
    return valid_refresh_tokens.get(refresh_token, "Invalid refresh token")

print(refresh_token("abc123"))
ANone
Bnew_access_token_1
CInvalid refresh token
Dnew_access_token_2
Attempts:
2 left
💡 Hint
Look at the dictionary keys and what the function returns when the key is found.
🧠 Conceptual
intermediate
1:30remaining
Which statement best describes the purpose of a refresh token?
Choose the best description of what a refresh token does in an authentication system.
AIt stores user credentials like username and password.
BIt grants permanent access to all resources without expiration.
CIt replaces the access token and is sent with every API request.
DIt is used to obtain a new access token after the old one expires.
Attempts:
2 left
💡 Hint
Think about what happens when an access token expires.
🔧 Debug
advanced
2:30remaining
Why does this token refresh code raise an error?
The code below is intended to refresh an access token but raises an error. What is the cause?
Rest API
valid_tokens = {"r1": "token1", "r2": "token2"}

def refresh_token(refresh_token):
    if refresh_token in valid_tokens:
        return valid_tokens[refresh_token]
    else:
        return "Invalid token"

print(refresh_token("r1"))
ANameError because valid_tokens is used before it is defined.
BTypeError because refresh_token is a function parameter and cannot be used as a variable.
CKeyError because 'r1' is not in valid_tokens.
DNo error; the code runs and prints 'token1'.
Attempts:
2 left
💡 Hint
Check the order of variable and function definitions.
📝 Syntax
advanced
2:30remaining
Which option correctly implements a token refresh function with error handling?
Select the code snippet that correctly returns a new access token or raises an exception if the refresh token is invalid.
A
def refresh_token(token):
    if token not in tokens:
        raise ValueError("Invalid token")
    return tokens[token]
B
def refresh_token(token):
    if token in tokens
        return tokens[token]
    else:
        raise ValueError("Invalid token")
C
def refresh_token(token):
    if token in tokens:
        return tokens[token]
    else
        raise ValueError("Invalid token")
D
def refresh_token(token):
    if token in tokens:
        return tokens[token]
    else:
        return ValueError("Invalid token")
Attempts:
2 left
💡 Hint
Look carefully at the syntax of if statements and raising exceptions.
🚀 Application
expert
3:00remaining
How many tokens will be valid after this refresh sequence?
Given the code below, how many tokens remain valid after refreshing 'r1' and 'r3'?
Rest API
valid_tokens = {"r1": "token1", "r2": "token2", "r3": "token3"}

# Refresh function invalidates old refresh token and issues a new one

def refresh_token(token):
    if token not in valid_tokens:
        return "Invalid token"
    new_token = f"token_new_{token}"
    del valid_tokens[token]
    valid_tokens[f"r_new_{token}"] = new_token
    return new_token

refresh_token("r1")
refresh_token("r3")
A4
B2
C3
D5
Attempts:
2 left
💡 Hint
Count tokens before and after refresh calls carefully.

Practice

(1/5)
1. What is the main purpose of a refresh token in a token refresh mechanism?
easy
A. To obtain a new access token without asking the user to log in again
B. To log out the user immediately
C. To store user passwords securely
D. To encrypt the access token

Solution

  1. Step 1: Understand the role of refresh tokens

    Refresh tokens are used to get new access tokens when the old ones expire without requiring the user to log in again.
  2. Step 2: Compare options with this role

    Only To obtain a new access token without asking the user to log in again describes this purpose correctly. Options A, C, and D describe unrelated or incorrect functions.
  3. Final Answer:

    To obtain a new access token without asking the user to log in again -> Option A
  4. Quick Check:

    Refresh token = renew access token without login [OK]
Hint: Refresh tokens renew access tokens silently [OK]
Common Mistakes:
  • Confusing refresh token with access token
  • Thinking refresh token logs out users
  • Believing refresh token stores passwords
2. Which HTTP method is typically used by clients to send a refresh token to the server for a new access token?
easy
A. GET
B. PUT
C. POST
D. DELETE

Solution

  1. Step 1: Identify the HTTP method for sending data securely

    POST is used to send data like refresh tokens in the request body securely to the server.
  2. Step 2: Eliminate other methods

    GET is for retrieving data, DELETE for removing resources, and PUT for updating. Refresh token requests usually send sensitive data, so POST is preferred.
  3. Final Answer:

    POST -> Option C
  4. Quick Check:

    Send refresh token securely = POST [OK]
Hint: Use POST to send refresh tokens securely [OK]
Common Mistakes:
  • Using GET which exposes tokens in URL
  • Confusing PUT with POST
  • Using DELETE which is for removal
3. Consider this simplified server response code snippet handling a refresh token request:
if refresh_token == valid_token:
    access_token = generate_new_token()
    return {"access_token": access_token, "status": 200}
else:
    return {"error": "Invalid refresh token", "status": 401}
What will be the output if refresh_token is invalid?
medium
A. {"access_token": "newtoken123", "status": 200}
B. {"error": "Invalid refresh token", "status": 401}
C. SyntaxError
D. {"status": 200}

Solution

  1. Step 1: Analyze the condition for refresh token validity

    If the refresh token matches the valid token, a new access token is generated and returned with status 200.
  2. Step 2: Check the else branch for invalid token

    If the token is invalid, the code returns an error message with status 401.
  3. Final Answer:

    {"error": "Invalid refresh token", "status": 401} -> Option B
  4. Quick Check:

    Invalid token returns error 401 [OK]
Hint: Invalid token triggers error response 401 [OK]
Common Mistakes:
  • Assuming new token is returned even if invalid
  • Confusing status codes 200 and 401
  • Expecting syntax errors from valid code
4. A developer wrote this code to refresh tokens but it always returns an error:
def refresh_access_token(refresh_token):
    if refresh_token = valid_token:
        return generate_new_token()
    else:
        return "Invalid token"
What is the main error in this code?
medium
A. Function should not take parameters
B. Missing return statement in else block
C. generate_new_token() is undefined
D. Using assignment (=) instead of comparison (==) in the if condition

Solution

  1. Step 1: Check the if condition syntax

    The code uses a single equals sign (=) which is assignment, not comparison. This causes a syntax error or logic error.
  2. Step 2: Confirm other parts are correct

    The else block has a return statement, generate_new_token() is assumed defined, and function parameters are correct.
  3. Final Answer:

    Using assignment (=) instead of comparison (==) in the if condition -> Option D
  4. Quick Check:

    Use '==' to compare, not '=' [OK]
Hint: Use '==' for comparison in conditions [OK]
Common Mistakes:
  • Confusing '=' with '==' in if statements
  • Assuming missing return in else
  • Thinking function parameters are wrong
5. You want to implement a token refresh endpoint that rejects refresh tokens if they are expired or revoked. Which approach best ensures security and proper token refresh?
hard
A. Store refresh tokens with expiration and revocation status; verify both before issuing new access tokens
B. Accept any refresh token and always issue a new access token
C. Only check if the refresh token exists in the database, ignore expiration
D. Issue new access tokens without any refresh token verification

Solution

  1. Step 1: Understand security needs for refresh tokens

    Refresh tokens must be checked for expiration and revocation to prevent misuse and unauthorized access.
  2. Step 2: Evaluate options for token verification

    Store refresh tokens with expiration and revocation status; verify both before issuing new access tokens includes both expiration and revocation checks, ensuring only valid tokens get new access tokens. Other options ignore important security checks.
  3. Final Answer:

    Store refresh tokens with expiration and revocation status; verify both before issuing new access tokens -> Option A
  4. Quick Check:

    Verify expiration and revocation for security [OK]
Hint: Check expiration and revocation before refresh [OK]
Common Mistakes:
  • Ignoring token expiration
  • Not checking if token is revoked
  • Issuing tokens without verification