spring-mvc - Controller 上的 Spring Security @PreAuthorize

标签 spring-mvc spring-security

我正在尝试在某些 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 上:

  • 可以使用简单的 Ant 匹配器轻松完成
  • 它强制您允许在 Controller 上进行代理,或者使用类代理而不是 JDK 代理,或者使用 Controller 接口(interface)

  • 恕我直言,@PreAuthorize最适合服务级别,因为您可以将域对象与用户授予的权限混合以获得细粒度的授权。

    关于spring-mvc - Controller 上的 Spring Security @PreAuthorize,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30529831/

    相关文章:

    Spring 安全/hibernate : Bad credentials even if they're right?

    grails - 为什么 Grails Spring Security channel 安全性将我的 Controller 名称替换为 'grails' ?

    java - Spring security Basic Authentication - 401 Unauthorized with correct credentials

    java - 哪种方法对碱基和排序速度更优?

    java - 从java服务器获取pdf页面,并嵌入到现有的html中

    java - 如何分析 spring mvc 应用程序的页面请求

    java - Spring Security 无法在 Windows 7 下运行

    java - 将 Spring Security 与 EJB 或 Spring 一起使用?

    java - 如何合并这两个 Spring Boot Controller ?

    spring-mvc - 在 JBoss 上使用 Spring MVC Java Config 时出现 404 错误