0
I’m working with Spring Secutiry. When I add this line below, I get 403 status 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’ve already put the annotation @Preauthorize("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 scroll.
@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;
}
}
In the database, how the user’s profile is being registered?
– Weslley Tavares
Thanks Denis but I managed to solve the problem by following this video, very good explanation. https://www.youtube.com/watch?v=MM14uwVhVhc
– Caio César