I'm having trouble working with the Spring Secutiry. When I add this line below, I get status 403 when I try to access the url.
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private CustonUsuarioDetailService custonUsuarioDetailService;
@Override
protected void configure(HttpSecurity http) throws Exception {
// Funciona
http
.authorizeRequests()
.antMatchers("/css/**", "/js/**", "/webjars/**","/resources/**").permitAll()
.antMatchers("/usuarios").hasAnyRole("ADMIN")
//Problema
.antMatchers("/usuario/getIndicador").hasAnyRole("ADMIN")
//
.anyRequest()
.authenticated()
.and()
.formLogin()
.loginPage("/login")
.defaultSuccessUrl("/home")
.permitAll()
.and()
.logout()
.logoutSuccessUrl("/login")
.permitAll()
.and()
.httpBasic();
}
In my controller, I have already put the @PreAuthorize annotation ("hasAnyRole ('ADMIN')) but it seems that security does not find the role.
@RestController
@RequestMapping(value = "/usuario")
public class UsuarioCtrl {
@Autowired
private UsuarioRepository usuarioRepository;
@GetMapping("getOne")
public ResponseEntity<?> getOne(String nome) {
return new ResponseEntity<>(usuarioRepository.findFirstByNome(nome), HttpStatus.OK);
}
@GetMapping("getIndicador")
@PreAuthorize("hasAnyRole('ADMIN')")
public ResponseEntity<?> getIndicador() {
return new ResponseEntity<>(usuarioRepository.count(), HttpStatus.OK);
}
}
Debugging this class, I checked that my user is returning a user with the expected role.
@Component
public class CustonUsuarioDetailService implements UserDetailsService {
private final UsuarioRepository usuarioRepository;
public CustonUsuarioDetailService(UsuarioRepository usuarioRepository) {
this.usuarioRepository = usuarioRepository;
}
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
//Recupero usuario pela identificação
Usuario usuario = Optional.ofNullable(usuarioRepository.findByIdentificacao(username)).orElseThrow(()-> new UsernameNotFoundException("Usuario não encontrado!"));
//Recupero permissoes
List<GrantedAuthority> permissoes = new ArrayList<>();
permissoes.add(new SimpleGrantedAuthority(usuario.getTipoUsuario().name()));
//Atribuo valores para User
User user = new User();
user.setAtivo(usuario.getStatus());
user.setNome(usuario.getNome());
user.setSenha(usuario.getSenha());
user.setLogin(usuario.getIdentificacao());
user.setPermissoes(permissoes);
return user;
}
}