【问题标题】:Spring security: deny access to resource to specific roleSpring security:拒绝访问特定角色的资源
【发布时间】:2018-10-03 08:12:55
【问题描述】:

我正在使用 Spring 编写一组 REST Web 服务,但无法针对某些逻辑使用 Spring 安全性对其进行配置。 我有这些类型的资源:

  • 无需验证即可访问的资源
  • 只有特定角色可以访问的资源
  • 某些角色无法访问资源

我对最后一个要求有疑问。我尝试了以下方法:

        http
        .authorizeRequests()  
            .antMatchers("/resource1").permitAll()                
            .antMatchers(HttpMethod.GET, "/resource2").hasAnyAuthority("ROLE_USER", "ROLE_ADMIN")
            .antMatchers(HttpMethod.GET, "/resource3").hasAuthority("ROLE_ADMIN")
            .antMatchers(HttpMethod.GET, "/resource4").not().hasAuthority("ROLE_USER")
            .anyRequest().fullyAuthenticated()
            .and().requestCache().requestCache(new NullRequestCache())
            .and().httpBasic().authenticationEntryPoint(authenticationEntryPoint)
            .and().csrf().disable();

这段代码和我需要的最相似:

  • 每个人都可以访问“resource1”,即使是未经身份验证的用户
  • 只有角色 USER 和 ADMIN 可以访问 resource2
  • 只有角色 ADMIN 可以访问资源3

但是,问题出在“resource4”...如果用户通过身份验证,一切正常(只有没有任何角色 USER 的用户可以访问资源)...问题是 Spring 允许访问 未经身份验证的用户(我想它认为他们不属于规则 USER,这是正确的)

关于如何将资源配置为某些角色无法访问但必须经过身份验证的任何想法?

【问题讨论】:

    标签: spring spring-security roles


    【解决方案1】:

    您可以使用.access(String expression),它允许指定 URL 由任意表达式保护

    with expression = "not( hasRole('USER') ) and isAuthenticated()"

    导致

    http
        .authorizeRequests()  
            .antMatchers("/resource1").permitAll()                
            .antMatchers(HttpMethod.GET, "/resource2").hasAnyAuthority("ROLE_USER", "ROLE_ADMIN")
            .antMatchers(HttpMethod.GET, "/resource3").hasAuthority("ROLE_ADMIN")
            .antMatchers(HttpMethod.GET,"/resource4").access("not( hasRole('USER') ) and isAuthenticated()")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-05-20
      • 2015-06-23
      • 2012-02-29
      • 2014-04-11
      • 2015-11-13
      • 2013-10-27
      • 2012-12-25
      • 2015-02-21
      相关资源
      最近更新 更多