Bird
Raised Fist0
Angularframework~20 mins

Interceptors for authentication tokens in Angular - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Interceptor Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2:00remaining
What does this Angular HTTP interceptor do?
Consider this Angular HTTP interceptor code. What is the main effect on outgoing HTTP requests?
Angular
import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler } from '@angular/common/http';

@Injectable({ providedIn: 'root' })
export class AuthInterceptor implements HttpInterceptor {
  intercept(req: HttpRequest<any>, next: HttpHandler) {
    const token = localStorage.getItem('authToken');
    if (token) {
      const cloned = req.clone({
        headers: req.headers.set('Authorization', `Bearer ${token}`)
      });
      return next.handle(cloned);
    }
    return next.handle(req);
  }
}
AIntercepts HTTP responses to check for token expiration and logs out the user.
BRemoves any Authorization header from outgoing HTTP requests to prevent token leaks.
CAdds an Authorization header with a Bearer token to all outgoing HTTP requests if a token exists in localStorage.
DModifies the request URL to include the token as a query parameter for authentication.
Attempts:
2 left
💡 Hint
Look at how the request is cloned and what header is added before sending.
📝 Syntax
intermediate
2:00remaining
Identify the syntax error in this Angular interceptor snippet
Which option correctly fixes the syntax error in this Angular HTTP interceptor code?
Angular
intercept(req: HttpRequest<any>, next: HttpHandler) {
  const token = localStorage.getItem('authToken');
  if(token) {
    const cloned = req.clone({
      headers: req.headers.set('Authorization', 'Bearer ' + token)
    });
    return next.handle(cloned);
  }
  return next.handle(req);
}
AAdd a missing semicolon after localStorage.getItem('authToken')
BChange req.clone to req.clone() with empty parentheses
CAdd a missing colon after the intercept method name
DAdd a missing comma after 'Authorization' in headers.set
Attempts:
2 left
💡 Hint
Check the line where token is assigned from localStorage.
🔧 Debug
advanced
2:30remaining
Why does this interceptor fail to add the token header?
This Angular interceptor is supposed to add an Authorization header but the header is missing in requests. What is the cause?
Angular
intercept(req: HttpRequest<any>, next: HttpHandler) {
  const token = localStorage.getItem('authToken');
  if (token) {
    req.headers.set('Authorization', `Bearer ${token}`);
  }
  return next.handle(req);
}
AHttpRequest objects are immutable; headers.set returns a new headers object but does not modify the original request.
BlocalStorage.getItem returns null if no token, causing a runtime error.
CThe interceptor must call next.handle() inside the if block only.
DThe Authorization header must be lowercase 'authorization' to be recognized.
Attempts:
2 left
💡 Hint
Think about how Angular HttpRequest objects handle immutability.
❓ state_output
advanced
2:30remaining
What is the output of this interceptor chain?
Given two interceptors registered in this order: AuthInterceptor adds Authorization header if token exists; LoggerInterceptor logs request headers. What will LoggerInterceptor log if localStorage has token 'abc123'?
Angular
AuthInterceptor intercept(req, next) {
  const token = localStorage.getItem('authToken');
  if (token) {
    const cloned = req.clone({ headers: req.headers.set('Authorization', `Bearer ${token}`) });
    return next.handle(cloned);
  }
  return next.handle(req);
}

LoggerInterceptor intercept(req, next) {
  console.log(req.headers.get('Authorization'));
  return next.handle(req);
}
ALoggerInterceptor logs null because headers are not set yet
BLoggerInterceptor logs 'Bearer abc123'
CLoggerInterceptor logs undefined due to missing header
DLoggerInterceptor logs an error because req.headers.get is not a function
Attempts:
2 left
💡 Hint
Remember interceptors run in the order they are registered.
🧠 Conceptual
expert
3:00remaining
Why use an HTTP interceptor for authentication tokens instead of adding headers manually in each service?
Which is the best reason to use an Angular HTTP interceptor to add authentication tokens rather than setting headers manually in every HTTP call?
AInterceptors allow tokens to be encrypted automatically without extra code.
BInterceptors improve HTTP request speed by caching tokens locally in the browser.
CInterceptors prevent the need for Angular services to import HttpClient.
DInterceptors centralize token handling, reduce code duplication, and automatically add tokens to all requests, improving maintainability and security.
Attempts:
2 left
💡 Hint
Think about code reuse and consistency across many HTTP calls.

Practice

(1/5)
1. What is the main purpose of an HTTP interceptor in Angular when dealing with authentication tokens?
easy
A. To create new HTTP requests manually
B. To automatically add authentication tokens to outgoing HTTP requests
C. To block all HTTP requests from the app
D. To change the URL of HTTP requests

Solution

  1. Step 1: Understand the role of interceptors

    Interceptors are used to modify HTTP requests or responses globally in Angular.
  2. Step 2: Identify the use of tokens in interceptors

    They commonly add authentication tokens to requests to keep the app secure without repeating code.
  3. Final Answer:

    To automatically add authentication tokens to outgoing HTTP requests -> Option B
  4. Quick Check:

    Interceptors add tokens = B [OK]
Hint: Interceptors modify requests automatically, especially for tokens [OK]
Common Mistakes:
  • Thinking interceptors create requests
  • Believing interceptors block requests
  • Assuming interceptors change URLs
2. Which of the following is the correct way to clone an HTTP request before adding an authentication token in an Angular interceptor?
easy
A. request.updateHeaders({ Authorization: 'Bearer ' + token })
B. request.headers.set('Authorization', 'Bearer ' + token)
C. request.modifyHeaders('Authorization', 'Bearer ' + token)
D. request.clone({ headers: request.headers.set('Authorization', 'Bearer ' + token) })

Solution

  1. Step 1: Recall Angular HttpRequest immutability

    HttpRequest objects are immutable, so you must clone them to modify headers.
  2. Step 2: Use the clone method with headers.set()

    The correct syntax is to call clone() and set the new header inside it.
  3. Final Answer:

    request.clone({ headers: request.headers.set('Authorization', 'Bearer ' + token) }) -> Option D
  4. Quick Check:

    Clone request with headers.set() = A [OK]
Hint: Always clone requests before changing headers [OK]
Common Mistakes:
  • Trying to modify headers directly without cloning
  • Using non-existent methods like modifyHeaders or updateHeaders
  • Not using the clone method
3. Given this Angular interceptor code snippet, what will be the Authorization header value in the outgoing HTTP request if the token is 'abc123'?
intercept(request: HttpRequest<any>, next: HttpHandler) {
  const token = 'abc123';
  const cloned = request.clone({
    headers: request.headers.set('Authorization', `Bearer ${token}`)
  });
  return next.handle(cloned);
}
medium
A. Authorization: Bearer abc123
B. Authorization: abc123
C. Authorization: Bearer token
D. No Authorization header will be added

Solution

  1. Step 1: Check how the token is added

    The code sets the Authorization header to 'Bearer ' plus the token string 'abc123'.
  2. Step 2: Understand string interpolation

    The template string `Bearer ${token}` becomes 'Bearer abc123'.
  3. Final Answer:

    Authorization: Bearer abc123 -> Option A
  4. Quick Check:

    Header value = 'Bearer abc123' [OK]
Hint: Template strings insert token value directly [OK]
Common Mistakes:
  • Forgetting 'Bearer ' prefix
  • Using the literal word 'token' instead of variable
  • Assuming header is not added
4. Identify the error in this Angular interceptor code that tries to add an auth token:
intercept(req: HttpRequest<any>, next: HttpHandler) {
  const token = 'xyz';
  req.headers.set('Authorization', 'Bearer ' + token);
  return next.handle(req);
}
medium
A. Headers are immutable; must clone request before setting headers
B. Token variable is not defined
C. next.handle() is missing a return statement
D. Authorization header should be lowercase

Solution

  1. Step 1: Understand HttpRequest immutability

    HttpRequest headers cannot be changed directly; they are immutable.
  2. Step 2: Correct way is to clone the request with new headers

    You must clone the request and set headers on the clone before passing it on.
  3. Final Answer:

    Headers are immutable; must clone request before setting headers -> Option A
  4. Quick Check:

    Immutable headers require cloning = A [OK]
Hint: Headers are immutable; clone request before modifying [OK]
Common Mistakes:
  • Trying to set headers directly on request
  • Ignoring immutability of HttpRequest
  • Not returning next.handle()
5. You want to create an Angular interceptor that adds an authentication token only to requests targeting your API domain 'api.example.com'. Which approach correctly implements this conditional logic?
hard
A. Modify the token inside next.handle() without cloning
B. Add the token to all requests unconditionally
C. Check if request.url.includes('api.example.com') before cloning and adding the token
D. Use a global variable to store the token and add it after the request completes

Solution

  1. Step 1: Identify the need for conditional token addition

    Only requests to 'api.example.com' should have the token added to avoid leaking tokens to other domains.
  2. Step 2: Use URL check before cloning and modifying request

    Check request.url.includes('api.example.com') and then clone the request with the token header.
  3. Step 3: Avoid modifying requests without cloning or adding tokens globally

    Modifying without cloning or adding tokens to all requests is insecure or incorrect.
  4. Final Answer:

    Check if request.url.includes('api.example.com') before cloning and adding the token -> Option C
  5. Quick Check:

    Conditional token addition by URL check = C [OK]
Hint: Add tokens only after checking request URL [OK]
Common Mistakes:
  • Adding tokens to all requests blindly
  • Modifying requests without cloning
  • Trying to add tokens after request completes
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard