Generate a scenario based coding snippet question having multiple choice options on…
- User
Generate a scenario based coding snippet question having multiple choice options on Spring Boot Filtration. Share the correct answer with reason for the same
- Assistant
Scenario:
You've been tasked with creating a user authentication filter in a Spring Boot application that intercepts all incoming HTTP requests to any endpoint starting with
/api/private/. For every request, the filter needs to check if the request has a valid authentication token in the header. The token must be prefixed with "Bearer " and then followed by the actual token string. If the token is missing or invalid, the filter should reject the request and return an HTTP 401 Unauthorized status.Here's a portion of the code for the filter:
import org.springframework.stereotype.Component; import org.springframework.web.filter.GenericFilterBean; import javax.servlet.*; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; @Component public class AuthenticationFilter extends GenericFilterBean { @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest httpRequest = (HttpServletRequest) request; HttpServletResponse httpResponse = (HttpServletResponse) response; String authHeader = httpRequest.getHeader("Authorization"); if (isValidToken(authHeader)) { chain.doFilter(request, response); } else { httpResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED); } } private boolean isValidToken(String authHeader) { // Assume this method correctly checks the token's validity // and returns true if valid and false if not. return true; } }You need to configure this filter so that it only applies to endpoints that start with
/api/private/. Which of the following configurations would correctly set up this filter?A. Annotating the filter class with
@WebFilter("/api/private/*")B. Modifying the
isValidTokenmethod to check for the specific URL patternC. Creating a new
FilterRegistrationBeanbean in a@ConfigurationclassD. Using
@ControllerAdviceto apply the filter globally and then checking the URL pattern within the filterCorrect Answer: C. Creating a new
FilterRegistrationBeanbean in a@ConfigurationclassReason:
Option A: The
@WebFilterannotation is used with servlets, but since we're working within Spring Boot, we would typically use aFilterRegistrationBeanto register our filter and specify the URL patterns it should apply to.Option B: Checking the URL pattern in the
isValidTokenmethod would not be appropriate because it's the responsibility of the filter configuration, not the token validation logic,
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.