Spring Boot中如何为指定REST接口URL禁用登录拦截?
Let's walk through modifying the three key files to achieve your goal—keeping security checks for all URLs except your target REST endpoint:
1. Update the Security Configuration Class
Assuming you're using Spring Security (the most common setup for Java apps), you need to add a permitAll() rule for your REST service's base path in the configure(HttpSecurity http) method. This tells the security filter to skip authentication for that route:
@Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() // Replace with your actual REST endpoint path(s) .antMatchers("/api/public-rest-service/**").permitAll() // All other URLs require authentication .anyRequest().authenticated() .and() .formLogin() // Keep your existing login page configuration .loginPage("/login") .permitAll() .and() .logout() .permitAll(); } }
- If you're using a different security framework like Apache Shiro, the logic is similar: add your REST path to a whitelist that bypasses authentication checks.
- For multiple REST endpoints, separate them with commas:
antMatchers("/api/service1/**", "/api/service2/**")
2. Verify JAX-RS Configuration
Make sure your JAX-RS application path aligns with the path you excluded in the security config. This ensures the routing matches the security rule:
@ApplicationPath("/api") public class JaxRsApplication extends Application { @Override public Set<Class<?>> getClasses() { Set<Class<?>> endpoints = new HashSet<>(); // Register your REST controller class here endpoints.add(PublicRestController.class); return endpoints; } }
The @ApplicationPath("/api") here pairs with the /api/public-rest-service/** rule in the security config—this consistency is crucial for the exclusion to work.
3. Check the REST Controller Path
Double-check your controller's @Path annotation to ensure it maps to the excluded route:
@Path("/public-rest-service") @Produces(MediaType.APPLICATION_JSON) public class PublicRestController { @GET @Path("/resource") public Response getPublicResource() { return Response.ok("This is public REST data—no login required!").build(); } }
The full path for this endpoint is /api/public-rest-service/resource, which falls under the /api/public-rest-service/** pattern we whitelisted earlier.
Bonus: Fix API Response Format
By default, some security frameworks redirect unauthenticated API requests to the login page (returning HTML instead of JSON). To fix this, add an authentication entry point to return a 401 JSON response for API requests:
http.exceptionHandling() .authenticationEntryPoint((request, response, authException) -> { // Check if the request expects JSON if (request.getHeader("Accept") != null && request.getHeader("Accept").contains("application/json")) { response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); response.setContentType("application/json"); response.getWriter().write("{\"error\": \"Unauthorized access to API\"}"); } else { // Redirect web requests to login page as before response.sendRedirect("/login"); } });
Quick Testing Tips
- Use tools like Postman or
curlto hit your REST endpoint—you should get a valid response without being redirected to the login page. - Try accessing a protected page (e.g.,
/dashboard) to confirm it still redirects to the login screen as expected.
内容的提问来源于stack exchange,提问作者vidarshana

