寻求Spring MVC中与PreProcessInterceptor等价的授权拦截器实现
org.jboss.resteasy.spi.interception.PreProcessInterceptor的方案及权限校验示例 Hey there! In Spring MVC, the equivalent component to JBoss Resteasy's PreProcessInterceptor (which runs logic before a request reaches your endpoint/controller) is the HandlerInterceptor interface (note that the older HandlerInterceptorAdapter is deprecated, so we'll use the interface directly). It allows you to execute custom logic right before the request is handed off to a controller method—exactly what you need for fetching user details and validating URL access permissions.
1. Custom HandlerInterceptor Implementation
Here's a complete example that fetches the current user, grabs the request URL, and validates access permissions:
import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.web.servlet.HandlerInterceptor; public class AccessControlInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { // Step 1: Fetch current authenticated user info Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); // Handle unauthenticated users (adjust this logic based on your auth setup) if (authentication == null || !authentication.isAuthenticated()) { response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized: Please log in first"); return false; } String username = authentication.getName(); // Optional: Get full user details and authorities // UserDetails userDetails = (UserDetails) authentication.getPrincipal(); // Collection<? extends GrantedAuthority> userAuthorities = userDetails.getAuthorities(); // Step 2: Get the target request URL String requestUrl = request.getRequestURI(); // You can also include the HTTP method for finer control: request.getMethod() // Step 3: Validate if the user has permission to access this URL if (!hasUserPermission(username, requestUrl)) { response.sendError(HttpServletResponse.SC_FORBIDDEN, "Forbidden: You don't have access to this resource"); return false; } // Permission granted—proceed to the controller return true; } /** * Custom permission validation logic (replace this with your business rules) * @param username Current authenticated username * @param requestUrl Target URL being accessed * @return True if user has permission, false otherwise */ private boolean hasUserPermission(String username, String requestUrl) { // Example rule: Admin can access all URLs; regular users only access /user/* endpoints if ("admin".equalsIgnoreCase(username)) { return true; } return requestUrl.startsWith("/user/"); } }
2. Register the Interceptor with Spring MVC
Next, you need to register your interceptor so Spring MVC uses it. Here's how to do it with Java-based configuration:
import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Configuration public class WebMvcConfiguration implements WebMvcConfigurer { @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(new AccessControlInterceptor()) // Apply interceptor to all requests .addPathPatterns("/**") // Exclude public endpoints (adjust these to match your app's public URLs) .excludePathPatterns("/login", "/logout", "/public/**", "/static/**"); } }
3. Key Notes
- User Info Source: The example uses Spring Security's
SecurityContextHolderto fetch the authenticated user. If you're using a custom auth setup (like session-stored users), replace this withrequest.getSession().getAttribute("yourUserAttributeKey"). - Permission Logic: The
hasUserPermissionmethod is a simple example—you can extend this to pull permissions from a database, config file, or external auth service for production use. - Alternatives: If you're already using Spring Security, you might also consider method-level security with
@PreAuthorize, butHandlerInterceptoris a closer match to Resteasy'sPreProcessInterceptorfor URL-based pre-processing.
内容的提问来源于stack exchange,提问作者Kathiresa J

