Spring Security中如何仅放行指定单个GET API接口?
Solution to Secure /api/appconsole/app/search and Permit Only /api/appconsole/app/{appid}
Got it, let's tweak your Spring Security configuration to achieve exactly what you need. The core thing to remember here is that Spring Security processes authorization rules in the order they're defined—so we just need to make sure we explicitly handle the two endpoints correctly before the catch-all rule.
Here's the adjusted configuration code:
httpSecurity.csrf().disable() .exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and() // Disable session creation since we're using stateless auth .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and() .authorizeRequests() // Allow access to static resources without auth .antMatchers( HttpMethod.GET, "/", "/file/**/*.*", "/*.html", "/favicon.ico", "/**/*.html", "/**/*.css", "/**/*.js" ).permitAll() // Explicitly permit GET requests to the appid endpoint .antMatchers(HttpMethod.GET, "/api/appconsole/app/{appid}").permitAll() // Explicitly deny unauthenticated access to the search endpoint (optional but improves readability) .antMatchers(HttpMethod.GET, "/api/appconsole/app/search").denyAll() // Allow OPTIONS pre-flight requests for API endpoints .antMatchers(HttpMethod.OPTIONS, "/api/**").permitAll() // Keep your existing permitted endpoints .antMatchers("/ws/**").permitAll() .antMatchers("/upload").permitAll() .antMatchers("/login/**").permitAll() .antMatchers("/registration/**").permitAll() .antMatchers("/api/orbeon/**").permitAll() // Require authentication for all other requests .anyRequest().authenticated();
Key Explanations:
- The
/api/appconsole/app/{appid}rule stays as-is—this uses Ant path matching to allow any GET request to that endpoint (where{appid}matches any single path segment) without authentication. - We added the
.antMatchers(HttpMethod.GET, "/api/appconsole/app/search").denyAll()rule right after the permitted endpoint. This explicitly blocks unauthenticated access to the search endpoint, and since it's defined before the catch-allanyRequest().authenticated()rule, it takes priority. - Even if you skipped the explicit
denyAllrule, theanyRequest().authenticated()would still require authentication for the search endpoint. But adding the explicit rule makes your configuration more readable and avoids accidental changes later (like if someone adjusts the catch-all rule).
内容的提问来源于stack exchange,提问作者Darshan Jain
相关产品推荐
相关产品推荐

