Bom estou fazendo um projeto a parte para treinar essa parte da autenticação e autorização mais estou tendo problema na hora de listar os usuários do banco de dados pois mesmo passando o token de acesso ele ainda continua mandando o 403.
Vou deixar os codigos abaixo:
@Entity
@Table(name = "tb_usuarios")
@AllArgsConstructor
@NoArgsConstructor
@Getter
@Setter
@EqualsAndHashCode(of = "id")
public class Usuario implements UserDetails {
@Id
@GeneratedValue(strategy = GenerationType.UUID)
private UUID id;
private String nome;
private String cpf;
private String email;
private String senha;
private UserRole role;
public Usuario(CadastroUsuarioDTO dados) {
this.nome = dados.nome();
this.cpf = dados.cpf();
this.email = dados.email();
this.senha = dados.senha();
this.role = UserRole.valueOf(dados.role());
}
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
if (this.role == UserRole.ADMIN) {
return List.of(new SimpleGrantedAuthority("ROLE_ADMIN"),
new SimpleGrantedAuthority("ROLE_USER"));
} else {
return List.of(new SimpleGrantedAuthority("ROLE_USER"));
}
}
@Override
public String getPassword() {
return senha;
}
@Override
public String getUsername() {
return email;
}
@Override
public boolean isAccountNonExpired() {
return true;
}
@Override
public boolean isAccountNonLocked() {
return true;
}
@Override
public boolean isCredentialsNonExpired() {
return true;
}
@Override
public boolean isEnabled() {
return true;
}
}
public enum UserRole {
ADMIN("Admin"),
USER("User");
private String role;
UserRole(String role) {
this.role = role;
}
public String getRole() {
return role;
}
}
public interface UsuarioRepository extends JpaRepository<Usuario, UUID> {
boolean existsByCpf(String cpf);
boolean existsByEmail(String email);
UserDetails findByEmail(String email);
}
@Service
@AllArgsConstructor
public class UsuarioService {
private final UsuarioRepository usuarioRepository;
private List<IValidarUsuario> validacao;
private final PasswordEncoder passwordEncoder;
@Transactional
public void salvar(Usuario usuario) {
usuario.setSenha(passwordEncoder.encode(usuario.getSenha()));
validacao.forEach(v -> v.validar(usuario));
usuarioRepository.save(usuario);
}
public List<Usuario> listar() {
return usuarioRepository.findAll();
}
}
@RestController
@RequestMapping("/usuario")
@AllArgsConstructor
public class UsuarioController {
private final UsuarioService usuarioService;
@PostMapping("/cadastrar")
public ResponseEntity cadastrar(@RequestBody @Valid CadastroUsuarioDTO dados) {
var usuario = new Usuario(dados);
usuarioService.salvar(usuario);
return ResponseEntity.ok().build();
}
@GetMapping("/listar")
public ResponseEntity<List<Usuario>> listar() {
List<Usuario> usuarios = usuarioService.listar();
return ResponseEntity.ok(usuarios);
}
}
@RestController
@RequestMapping("/auth")
@AllArgsConstructor
public class AuthenticationController {
private final AuthenticationManager authenticationManager;
private final TokenService tokenService;
@PostMapping("/login")
public ResponseEntity login(@RequestBody @Valid AuthenticationDTO data) {
var usernamePassword = new UsernamePasswordAuthenticationToken(data.email(), data.senha());
var auth = this.authenticationManager.authenticate(usernamePassword);
var token = tokenService.gerarToken((Usuario) auth.getPrincipal());
return ResponseEntity.ok(new LoginResponseDTO(token));
}
}
@Service
@AllArgsConstructor
public class AuthorizationService implements UserDetailsService {
private final UsuarioRepository usuarioRepository;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
return usuarioRepository.findByEmail(username);
}
}