【问题标题】:Spring security authorization based on ROLES not working基于 ROLES 的 Spring 安全授权不起作用
【发布时间】:2016-08-04 12:53:53
【问题描述】:

在 Spring boot / spring security / Angular JS 应用程序中..

我试图仅在用户具有指定角色时才允许以下页面。

.antMatchers("/1_reportingEntities/*.html").hasAnyRole(roles)

但即使没有为用户设置该角色,它也允许该页面。 我错过了什么?

Java 代码

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        String roles [] = new String[] {"ROLE_EDITOR", "ROLE_AUTHORISER" };

        http.httpBasic()
                .and()
                .authorizeRequests()

                // Permit these resources
                .antMatchers("/login", "/4_security/login.html", "/bower_components/**", "/0_common/*.html", "/1_reportingEntities/*.js",
                        "/2_dataCollections/*.js", "/3_calendar/*.js", "/4_security/*.js", "/")
                .permitAll()
                // All other requests needs authentication
                .anyRequest().authenticated()

                // Allow only if has certain roles  
                .antMatchers("/1_reportingEntities/*.html").hasAnyRole(roles)

                .and()
                // CSRF protection
                .csrf().csrfTokenRepository(csrfTokenRepository()).and().addFilterAfter(csrfHeaderFilter(), CsrfFilter.class);

        // Enable https
        http.requiresChannel().anyRequest().requiresSecure();

    }

【问题讨论】:

  • 我认为 spring 会自动为角色添加 ROLE_,尝试使用数组 {"EDITOR", "AUTHORISER"}
  • 无论你是否在它前面加上 ROLE 都没关系,Spring 可以检测到。
  • 试试把 antMatchers.hasAnyRole 放在 anyRequest.authenticated 之前,看看是否有效?

标签: java angularjs spring spring-security spring-boot


【解决方案1】:

我想问题出在 Spring 上。您需要将 hasAnyRole() 更改为 hasAnyAuthority()。

【讨论】:

  • 非常感谢您的工作。如果验证失败,因为用户没有有效角色,知道如何显示错误消息/页面吗?
【解决方案2】:

Spring 会在检查 hasAnyRole 时自动添加前缀 ROLE_,而 hasAnyAuthority 不会。

因此,在您的示例中,当您使用 hasAnyRole({"ROLE_EDITOR", "ROLE_AUTHORISER" }) 时,Spring 将实际检查您的用户是否具有任一角色 {"ROLE_ROLE_EDITOR", "ROLE_ROLE_AUTHORISER" }

您可以使用hasAnyRole({"EDITOR", "AUTHORISER"}),这将检查您的用户是否已被授予{"ROLE_EDITOR", "ROLE_AUTHORISER"},或者您可以继续指定{"ROLE_EDITOR", "ROLE_AUTHORISER" },但使用hasAnyAuthority.

【讨论】:

    猜你喜欢
    • 2011-12-04
    • 2019-06-15
    • 2020-11-29
    • 1970-01-01
    • 2012-07-24
    • 2017-05-10
    • 2012-04-07
    • 1970-01-01
    相关资源
    最近更新 更多