Spring Security无法正常工作

时间:2018-05-18 19:20:17

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

  @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“)时,它就会拒绝该角色的访问权限。我得到了     {     “timestamp”:1526671066818,     “状态”:403,     “错误”:“禁止”,     “消息”:“访问被拒绝”,     “path”:“/ users” }

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

1 个答案:

答案 0 :(得分:0)

你需要在两者之间小心

finishAffinity();
  

如果当前主体具有指定的角色,则返回true。通过   默认情况下,如果提供的角色不是以' ROLE _'这将是   添加。这可以通过修改defaultRolePrefix来自定义   DefaultWebSecurityExpressionHandler。

 hasRole([role])
  

如果当前主体具有指定的权限

,则返回true

第一个将默认添加" ROLE _"到指定的值

所以我会改为hasAuthority([authority])

Documentation