SpringBoot 获取 HttpSecurity 放行 URL 和 Method
在 SpringBoot 中获取 HttpSecurity 放行的 URL 和 Method 可以使用以下两种方法:
- 在
WebSecurityConfigurerAdapter中重写configure(HttpSecurity http)方法,然后通过http.authorizeRequests()设置需要放行的 URL 和 Method。
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable()
.authorizeRequests()
.antMatchers(HttpMethod.GET, '/api/public/**').permitAll()
.antMatchers(HttpMethod.POST, '/api/public/**').permitAll()
.anyRequest().authenticated()
.and()
.httpBasic();
}
}
上面的代码中,我们放行了 /api/public/ 目录下的所有 GET 和 POST 请求。
- 在 Controller 层中通过注解获取放行的 URL 和 Method。
@RestController
@RequestMapping('/api')
public class MyController {
@GetMapping('/public')
public String getPublic() {
return 'This is a public URL';
}
@PostMapping('/private')
public String postPrivate() {
return 'This is a private URL';
}
@GetMapping('/urls')
@PreAuthorize('hasRole('ADMIN')')
public List<String> getUrls(HttpServletRequest request) {
return request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE);
}
}
上面的代码中,我们使用了 @PreAuthorize 注解来限制只有 ADMIN 角色才能访问 /getUrls 接口,并通过 HttpServletRequest 的 getAttribute 方法获取了当前请求的 URL 和 Method。
原文地址: https://www.cveoy.top/t/topic/nbdE 著作权归作者所有。请勿转载和采集!