403: Access is denied / Spring security

Asked

Viewed 296 times

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?

  • Thanks Denis but I managed to solve the problem by following this video, very good explanation. https://www.youtube.com/watch?v=MM14uwVhVhc

1 answer

0

Spring Security uses the feature AccessDecisionManager for access control. This feature in turn implements the RoleVoter default of the framework itself. When using the default implementation (which appears to be your case), you need to use the prefix "ROLE_" next to the user profile itself.

Another way around this situation would be to customize the access control of Spring Security, creating your own AccessDecisionManager. For this you need to inform Spring Security itself that the access manager will now be the one you created.

Here is an example of how to implement your own manager:

public class MeuGerenciadorDeAcesso  extends AffirmativeBased {
    public MeuGerenciadorDeAcesso() {
        super();
        List<AccessDecisionVoter> decisionVoters = new ArrayList<AccessDecisionVoter>();
        RoleVoter roleVoter = new MyCustomRoleVoter();
        decisionVoters.add(roleVoter);
        AuthenticatedVoter authenticatedVoter = new AuthenticatedVoter();
        decisionVoters.add(authenticatedVoter);
        setDecisionVoters(decisionVoters);
    }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.