我尝试在使用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("/");
我实现了UserDetailsService
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,可以无问题地访问/报告...它不应该。
什么不能正常工作?
答案 0 :(得分:0)
尝试
http.authorizeRequests().antMatchers("/report/**").hasAuthority("ROLE_ADMIN");
更新:(以上答案无效)
尝试以下代码
http.authorizeRequests()
.antMatchers("/report/**").access("hasRole('ROLE_ADMIN')")
.anyRequest().fullyAuthenticated()