访问URL的角色

时间:2016-06-18 04:07:16

标签: spring spring-security

我尝试在使用springsecurity的Spring启动应用程序中添加角色

在扩展WebSecurityConfigurerAdapter

的类中

在configure方法中,我有

http.authorizeRequests().antMatchers("/rest/**").authenticated();
http.authorizeRequests().antMatchers("/report/**").hasRole("ADMIN");
http.csrf().disable();
http.exceptionHandling().authenticationEntryPoint(authenticationEntryPoint);
http.formLogin().successHandler(authenticationSuccessHandler);   http.formLogin().failureHandler(authenticationFailureHandler);
http.logout().logoutUrl("/logout");
http.logout().logoutSuccessUrl("/");

我实现了UserDetailsS​​ervice

public class UserServiceImpl implements UserDetailsService, UserService {
    @Override
    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {

    UserApp userapp = repository.findByUsername(userName);

    if (userapp == null) {
        throw new UsernameNotFoundException("Username " + userName + " not found");
    }

    return new CustomUserDetails(userapp);
    }
}


public class UserApp {
    ...
    ...
    @Enumerated(EnumType.STRING)
    private RoleEnum role;
}

public enum RoleEnum {
    ROLE_ADMIN, ROLE_USER;
}


public class CustomUserDetails implements UserDetails {
    private final UserApp userApp;

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        Collection<GrantedAuthority> authorities = new ArrayList<>();
        RoleEnum userRole = this.userApp.getRole();

        if (userRole != null) {
            SimpleGrantedAuthority authority = new SimpleGrantedAuthority(userRole.name());
            authorities.add(authority);
        }
        return authorities;
    }
}

我的用户有ROLE_USER,可以无问题地访问/报告...它不应该。

什么不能正常工作?

1 个答案:

答案 0 :(得分:0)

尝试

http.authorizeRequests().antMatchers("/report/**").hasAuthority("ROLE_ADMIN");

更新:(以上答案无效)

尝试以下代码

http.authorizeRequests()
    .antMatchers("/report/**").access("hasRole('ROLE_ADMIN')")
    .anyRequest().fullyAuthenticated()