package br.com.alura.forum.controller.dto;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
public class LoginForm {
public String email;
public String senha;
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getSenha() {
return senha;
}
public void setSenha(String senha) {
this.senha = senha;
}
public UsernamePasswordAuthenticationToken converter() {
return new UsernamePasswordAuthenticationToken(email, senha);
}
}
package br.com.alura.forum.controller;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import br.com.alura.forum.config.security.TokenService;
import br.com.alura.forum.controller.dto.LoginForm;
import br.com.alura.forum.controller.dto.TokenDto;
@RestController
@RequestMapping("/auth")
public class AutenticacaoController {
@Autowired
private AuthenticationManager authManager;
@Autowired
private TokenService tokenService;
@PostMapping
public ResponseEntity<TokenDto> autenticar(@RequestBody @Valid LoginForm form){
UsernamePasswordAuthenticationToken dadosLogin = form.converter();
System.out.println(form.getEmail());
System.out.println(form.getSenha());
try {
Authentication authentication = authManager.authenticate(dadosLogin);
String token = tokenService.gerarToken(authentication);
return ResponseEntity.ok(new TokenDto(token,"Bearer"));
}catch(AuthenticationException e) {
return ResponseEntity.badRequest().build();
}
}
}