403: Access is denied / Spring security

0

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;
    }
}
    
asked by anonymous 05.04.2018 / 18:10

1 answer

0

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

Another way to get around this would be to customize Spring Security access control, creating your own AccessDecisionManager . To do this, you must tell Spring Security itself that the access manager will now be what you have 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);
    }
}
    
05.04.2018 / 23:53