【问题标题】:Spring Security restricting access to certain roles at certain url levels [duplicate]Spring Security 在某些 url 级别限制对某些角色的访问 [重复]
【发布时间】:2020-12-19 22:15:34
【问题描述】:

我正在尝试了解 Spring Security,并且我有一个页面要求您在启动时登录,然后用户具有角色。我想说所有角色都可以访问欢迎页面,但如果您想登录管理页面,那么您只能是 EMPLOYEE 或 USER。

这里是配置方法:

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        
        http.authorizeRequests().antMatchers("/*").hasAnyRole("EMPLOYEE", "USER","NONE1")
        
                .antMatchers("/courierapp/admin").hasAnyRole("EMPLOYEE","USER")
        
                .anyRequest().authenticated()

                .and().formLogin();     
    }

例如,如果我的角色为“NONE1”,为什么 /courierapp/admin 仍然可以访问?

【问题讨论】:

  • 只要您拥有任何其他角色,您就可以访问。
  • @M.Deinum 我没有听懂你在说什么。该用户只有 NONE1 并且即使不是员工也不是用户也可以访问 admin。为什么会这样?我的语法错了吗?
  • 您的问题并不清楚。此外,如果 /courierapp 是应用程序(或基础)的名称,则您的 URL 应为 /admin,这将使第一个 /* 匹配,您需要颠倒顺序。

标签: spring spring-security


【解决方案1】:

如果其他人在使用 antMatchers 时遇到 Spring Security 问题,这是第一个匹配项,所以在这种情况下我必须这样做:

@Override
    protected void configure(HttpSecurity http) throws Exception {
        
        http.authorizeRequests()
                .antMatchers("/admin").hasAnyRole("EMPLOYEE","USER")
                .antMatchers("/").hasAnyRole("EMPLOYEE", "USER","NONE1")
                .anyRequest().authenticated()
                .and().formLogin(); 
    }

这使得只有员工和用户才能访问 /admin。另外,如果你的 url 中有一个基本路径,而你不知道它来自哪里,那只是根路径。

【讨论】:

  • 在这种情况下没关系。但是 /courierapp/admin/admin 是完全不同的 URL。
猜你喜欢
  • 2022-11-26
  • 1970-01-01
  • 2012-12-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-05
  • 2016-07-07
  • 1970-01-01
相关资源
最近更新 更多