【问题标题】:Spring Security not working properlySpring Security 无法正常工作
【发布时间】:2018-10-29 06:54:00
【问题描述】:
  @Override
protected void configure(HttpSecurity http) throws Exception {
    http
            .authorizeRequests()
            .antMatchers("/entrysheet/**").permitAll()//.hasRole("USER")
            .antMatchers("/users/**").hasRole("ADMIN") //Needs to be first
            .anyRequest().authenticated()
    ;
}


@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

@Autowired
UsersRepository usersRepository;

@Bean
public UserDetailsService userDetailsService() {
    System.out.println("fdsfdsfsd");
    InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();
    usersRepository.findAll().forEach(users -> {
        UserDetails userDetails = User.withUsername(users.getUsername()).password(users.getPassword())
                .roles((users.getIdRole() != null && users.getIdRole() == 1) ? "ADMIN" : "USER").build();
        System.out.println(userDetails.getUsername() + " " + userDetails.getPassword() +
                userDetails.getAuthorities());

        manager.createUser(userDetails);
            }
    );

    return manager;
}


@Override
protected void configure(HttpSecurity http) throws Exception {
    http
            .authorizeRequests()
           //.antMatchers("/entrysheet/**").permitAll().anyRequest().authenticated()//.hasRole("USER")
           //.antMatchers("/users/**").hasRole("ADMIN") //Needs to be first
            .antMatchers("/", "/**").permitAll() //Permit all other roles to all other paths
            .anyRequest().authenticated()

            //.authorizeRequests()
            //.antMatchers("/entrysheet/**").permitAll()//.hasRole("USER")
            //.antMatchers("/users/**").hasRole("ADMIN") //Needs to be first
            //.anyRequest().authenticated()


    ;
}

}

这是我的配置。但似乎 /users/ 不能被任何人访问。

每当我输入“.hasRole("RoleName")”时,它都会拒绝对该角色的访问。我得到一个 { “时间戳”:1526671066818, “状态”:403, “错误”:“禁止”, "message": "拒绝访问", “路径”:“/用户” }

从那。

我想要的是某些请求只允许“USER”访问,例如:“/entrysheet”、“/datasheet”等,而“ADMIN”只能访问“/users”

【问题讨论】:

  • 但似乎 /users/ 不能被任何人访问。 当然,您配置了.antMatchers("/users/**").hasRole("ADMIN"),因此只有角色为ADMIN 的用户才能访问该URL。
  • @dur 它也没有被 ADMIN 访问。

标签: spring rest spring-boot spring-security http-status-code-403


【解决方案1】:

两者之间需要小心

 hasRole([role])

如果当前主体具有指定角色,则返回 true。经过 如果提供的角色不以“ROLE_”开头,则默认为 添加。这可以通过修改 defaultRolePrefix on DefaultWebSecurityExpressionHandler。

或

hasAuthority([authority])

如果当前主体具有指定的权限,则返回 true

第一个默认情况下将“ROLE_”添加到指定的值

所以我会改为hasAuthority

Documentation

【讨论】:

    猜你喜欢
    • 2017-04-29
    • 2020-02-09
    • 2021-09-20
    • 2013-05-06
    • 2017-03-05
    • 1970-01-01
    • 2013-09-25
    • 2019-06-29
    • 2023-04-08
    相关资源
    最近更新 更多