CÓDIGO QUE FAZ A BUSCA NO BANCO
@Override
public Usuario buscaPorEmail(String email) {
try {
PreparedStatement stmt = connection.prepareStatement("SELECT ID, NOME, SENHA FROM USUARIO WHERE EMAIL = ?");
stmt.setString(1, email);
Usuario usuario = new Usuario();
ResultSet rs = stmt.executeQuery();
rs.next();
usuario.setId(rs.getString(1));
usuario.setNome(rs.getString(2));
usuario.setSenha(rs.getString(3));
rs.close();
return usuario;
} catch (SQLException e) {
System.out.println(e.getMessage());
return null;
} finally {
fechar();
}
}
CLASSE AUTENTICAÇÃO CONTROLLER
@RestController
@RequestMapping("/auth")
public class AutenticacaoController {
@Autowired
private AuthenticationManager authManager;
@Autowired
private TokenService tokenService;
@PostMapping
public ResponseEntity<TokenDTO> autenticar(@RequestBody LoginForm form) {
UsernamePasswordAuthenticationToken dadosLogin = form.converter();
try {
Authentication authentication = authManager.authenticate(dadosLogin);
String token = tokenService.gerarToken(authentication);
return ResponseEntity.ok(new TokenDTO(token, "Bearer"));
} catch (AuthenticationException e) {
System.out.println("EXCEÇÃO: " + e.getMessage() + "STACKTRACE: " + e.getStackTrace()[0]);
return ResponseEntity.badRequest().build();
}
}
}
CÓDIGO QUE GERA O TOKEN
public String gerarToken(Authentication authentication) {
Usuario logado = (Usuario) authentication.getPrincipal();
Date hoje = new Date();
Date dataExpiracao = new Date(hoje.getTime() + 300000);
return Jwts.builder()
.setIssuer("API")
.setSubject(logado.getId().toString())
.setIssuedAt(hoje)
.setExpiration(dataExpiracao)
.signWith(SignatureAlgorithm.HS256, secret)
.compact();
}
MÉTODO CONFIGURE
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers(HttpMethod.POST, "/auth").permitAll()
.antMatchers(HttpMethod.POST, "/usuario/cadastra").permitAll()
.anyRequest().authenticated()
.and().csrf().disable()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and().addFilterBefore(new AutenticacaoViaTokenFilter(tokenService, usuarioRepository), UsernamePasswordAuthenticationFilter.class);
}