我正在尝试在某些 Controller 上使用与 @PreAuthorize("permitAll") 匹配的 url(基于 Ant ),即
@Controller
@RequestMapping("/register")
public class RegistrationController {
...
@PreAuthorize("permitAll")
@RequestMapping(method = RequestMethod.GET)
public String register() { ... }
安全配置:
@Configuration
@EnableWebMvcSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests()
.antMatchers("/").permitAll()
.anyRequest().authenticated()
我还尝试将 @EnableGlobalMethodSecurity 添加到我的 MVC 配置中:
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class MvcConfig extends WebMvcConfigurerAdapter { ... }
但这没有效果
但是,在点击/register 时仍然提示我进行身份验证。如果我将“/register”添加到 Ant 匹配器中,它可以工作,即 .antMatchers("/", "/register").permitAll()
我在这里想念什么? @PreAuthorize 似乎对我的 Controller 没有影响
最佳答案
你不能这样做,因为 Ant 匹配器和 @PreAuthorize
在不同的层次上工作。
Ant 匹配器工作在 http 安全级别。 Spring 安全过滤器查看请求,如果发现应该拒绝访问,它甚至不将请求传递给调度程序 servlet,直接发送 403 错误。PreAuthorize
在方法级别工作。当一个方法即将被调用时,一个 AOP 代理控制是否应该允许访问。所以 2 个授权级别是 链式 ,而不是第二个覆盖第一个。
无论如何,我强烈建议你不是 使用 @PreAuthorize("hasRole('ADMIN')")
在 Controller 上:
恕我直言,
@PreAuthorize
最适合服务级别,因为您可以将域对象与用户授予的权限混合以获得细粒度的授权。
关于spring-mvc - Controller 上的 Spring Security @PreAuthorize,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30529831/