【问题标题】:Spring-boot REST security config roles don't work rightSpring-boot REST 安全配置角色无法正常工作
【发布时间】:2019-05-31 10:55:50
【问题描述】:

只有具有管理员角色的用户应该能够在“users/all”发出请求,但基本用户也可以。 这是我的安全配置:

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.csrf().disable();
    http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);

    http
            .authorizeRequests()
            .antMatchers(HttpMethod.POST, "/users/**").permitAll()
            .antMatchers( "/users/all").authenticated().anyRequest().hasAnyRole("ADMIN")
            .antMatchers("/users/me").authenticated().anyRequest().hasAnyRole("ADMIN", "BASIC_USER")
            .and()
            .formLogin().disable()
            .httpBasic();
}

This is the request from Postman

为什么我可以向基本用户提出请求?

如果我把它们按这个顺序排列:

.antMatchers( "/users/all").authenticated().anyRequest().hasAnyRole("ADMIN")
 .antMatchers("/users/me").authenticated().anyRequest().hasAnyRole("ADMIN", "BASIC_USER")
  .antMatchers(HttpMethod.POST, "/users/**").permitAll()

还是一样,但是 /me 请求不再起作用了。

/all request /me request

现在 /me 请求响应为 403。

【问题讨论】:

    标签: rest http spring-boot spring-security basic-authentication


    【解决方案1】:
    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return this.user.getRoles().stream().map(role -> new SimpleGrantedAuthority(String.format("ROLE_%s", role.getRole()))).collect(Collectors.toList());
    }
    

    我将 role 更改为 role.getRole()

    【讨论】:

      【解决方案2】:

      你能换行吗,管理员限制是上限?

      【讨论】:

      • 我也有同样的问题。
      猜你喜欢
      • 2020-09-05
      • 2019-11-15
      • 2023-04-08
      • 2017-03-05
      • 1970-01-01
      • 2021-09-16
      • 2021-11-02
      • 2020-02-09
      • 2019-01-23
      相关资源
      最近更新 更多