Bird
Raised Fist0
Rest APIprogramming~20 mins

Bearer token authentication 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
🎖️
Bearer Token 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 Bearer token check?
Given this Python Flask snippet checking a Bearer token, what will be the response if the token is 'abc123'?
Rest API
from flask import Flask, request, jsonify
app = Flask(__name__)

@app.route('/data')
def data():
    auth = request.headers.get('Authorization')
    if auth == 'Bearer abc123':
        return jsonify({'message': 'Access granted'})
    else:
        return jsonify({'message': 'Access denied'}), 401

# Simulate a request with header Authorization: Bearer abc123
response = None
class DummyRequest:
    headers = {'Authorization': 'Bearer abc123'}
request = DummyRequest()

if request.headers.get('Authorization') == 'Bearer abc123':
    response = {'message': 'Access granted'}
else:
    response = {'message': 'Access denied'}

print(response)
A{"message": "Access granted"}
B{"message": "Access denied"}
C401 Unauthorized error
DNone
Attempts:
2 left
💡 Hint
Check the exact match of the Authorization header value.
🧠 Conceptual
intermediate
1:30remaining
What does the 'Bearer' keyword signify in the Authorization header?
In the HTTP header 'Authorization: Bearer ', what is the role of the word 'Bearer'?
AIt indicates the type of token used for authentication.
BIt is the actual token value.
CIt specifies the encryption method of the token.
DIt is a username prefix.
Attempts:
2 left
💡 Hint
Think about how HTTP headers specify token types.
🔧 Debug
advanced
2:30remaining
Why does this Bearer token check always fail?
Identify the error in this Python code snippet that checks a Bearer token from headers: headers = {'Authorization': 'Bearer abc123'} token = headers.get('Authorization') if token == 'abc123': print('Access granted') else: print('Access denied')
AThe headers dictionary is missing the Authorization key.
BThe comparison should use 'Bearer abc123' instead of 'abc123'.
CThe token variable includes 'Bearer ' prefix, so direct comparison to 'abc123' fails.
DThe code raises a KeyError because get() is not used.
Attempts:
2 left
💡 Hint
Check what the token variable actually contains.
📝 Syntax
advanced
2:00remaining
Which option correctly extracts the Bearer token from the Authorization header?
Given a header string 'Authorization: Bearer abc123', which Python code correctly extracts 'abc123'?
Atoken = header.split(':')[1]
Btoken = header.replace('Bearer', '')
Ctoken = header[7:]
Dtoken = header.split(' ')[1]
Attempts:
2 left
💡 Hint
Split the string by space and take the second part.
🚀 Application
expert
3:00remaining
How many valid tokens are accepted by this Bearer token validation code?
Consider this Python code snippet: valid_tokens = {'token1', 'token2', 'token3'} header = 'Bearer token2' if header.startswith('Bearer '): token = header[7:] if token in valid_tokens: result = 'Access granted' else: result = 'Access denied' else: result = 'No token provided' print(result) How many tokens from the valid_tokens set will result in 'Access granted' if used in the header?
A0
B3
C1
D2
Attempts:
2 left
💡 Hint
All tokens in valid_tokens are accepted if header starts with 'Bearer '.

Practice

(1/5)
1. What is the main purpose of a Bearer token in REST API authentication?
easy
A. To prove the identity of the client making the request
B. To encrypt the data sent between client and server
C. To specify the format of the response data
D. To define the API endpoint URL

Solution

  1. Step 1: Understand Bearer token role

    A Bearer token is a secret key sent with requests to prove who the client is.
  2. Step 2: Identify main purpose

    It helps the server know the client's identity and permissions.
  3. Final Answer:

    To prove the identity of the client making the request -> Option A
  4. Quick Check:

    Bearer token = client identity proof [OK]
Hint: Bearer tokens prove who you are, not encrypt data [OK]
Common Mistakes:
  • Thinking Bearer tokens encrypt data
  • Confusing token with API endpoint
  • Assuming token defines response format
2. Which of the following is the correct way to include a Bearer token in an HTTP request header?
easy
A. Token: Bearer your_token_here
B. Authorization: Bearer your_token_here
C. Authorization: Token your_token_here
D. Bearer: Authorization your_token_here

Solution

  1. Step 1: Recall Bearer token header format

    The standard way is to use the 'Authorization' header with the word 'Bearer' followed by the token.
  2. Step 2: Match correct syntax

    Authorization: Bearer your_token_here matches the correct syntax: 'Authorization: Bearer your_token_here'.
  3. Final Answer:

    Authorization: Bearer your_token_here -> Option B
  4. Quick Check:

    Authorization header + Bearer keyword = correct format [OK]
Hint: Use 'Authorization: Bearer <token>' exactly [OK]
Common Mistakes:
  • Using 'Token' instead of 'Bearer'
  • Swapping header name and value order
  • Omitting 'Bearer' keyword
3. Given this Python code snippet using the requests library, what will be the output if the token is invalid?
import requests
headers = {"Authorization": "Bearer invalid_token"}
response = requests.get("https://api.example.com/data", headers=headers)
print(response.status_code)
medium
A. 200
B. 404
C. 401
D. 500

Solution

  1. Step 1: Understand HTTP status codes for authentication

    401 means Unauthorized, which is returned when authentication fails due to invalid token.
  2. Step 2: Analyze the code behavior with invalid token

    The server will reject the request and respond with 401 Unauthorized status code.
  3. Final Answer:

    401 -> Option C
  4. Quick Check:

    Invalid token = 401 Unauthorized [OK]
Hint: Invalid token usually returns 401 status code [OK]
Common Mistakes:
  • Assuming 200 means success with invalid token
  • Confusing 404 Not Found with authentication error
  • Thinking server error 500 occurs for invalid token
4. You wrote this code to send a Bearer token but the server always responds with 401 Unauthorized. What is the likely error?
headers = {"Authorization": "bearer mytoken123"}
response = requests.get(url, headers=headers)
medium
A. The URL is incorrect
B. The token string is missing
C. The header name should be 'Token' instead of 'Authorization'
D. The word 'bearer' should be capitalized as 'Bearer'

Solution

  1. Step 1: Check Bearer token header case sensitivity

    The 'Bearer' keyword in the Authorization header is case sensitive and must be capitalized.
  2. Step 2: Identify the error in the code

    The code uses 'bearer' in lowercase, causing the server to reject the token and respond 401.
  3. Final Answer:

    The word 'bearer' should be capitalized as 'Bearer' -> Option D
  4. Quick Check:

    Bearer keyword is case sensitive [OK]
Hint: Capitalize 'Bearer' exactly in Authorization header [OK]
Common Mistakes:
  • Using lowercase 'bearer' keyword
  • Changing header name from 'Authorization'
  • Ignoring token format errors
5. You want to secure an API endpoint so only requests with a valid Bearer token can access it. Which of these is the best approach to implement this in your REST API server?
hard
A. Check the 'Authorization' header for a Bearer token, validate it, and reject requests without valid tokens
B. Allow all requests but log the Bearer token if present
C. Require the token as a URL query parameter instead of header
D. Ignore tokens and rely on IP address filtering

Solution

  1. Step 1: Understand secure API access with Bearer tokens

    Secure APIs check the Authorization header for a valid Bearer token to authenticate requests.
  2. Step 2: Identify best practice for token validation

    Rejecting requests without valid tokens ensures only authorized clients access the endpoint.
  3. Final Answer:

    Check the 'Authorization' header for a Bearer token, validate it, and reject requests without valid tokens -> Option A
  4. Quick Check:

    Validate token in Authorization header to secure API [OK]
Hint: Validate Bearer token in Authorization header to secure API [OK]
Common Mistakes:
  • Using query parameters for tokens (less secure)
  • Allowing requests without token validation
  • Relying on IP filtering alone