package br.com.alura.forum.config.security;
import java.util.Date;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;
import br.com.alura.forum.modelo.Usuario;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
@Service
public class TokenService {
@Value("${forum.jwt.expiration}")
private String expiration;
@Value("${forum.jwt.secret}")
private String secret;
public String gerarToken(Authentication auth) {
Usuario user = (Usuario) auth.getPrincipal();
Date hoje = new Date();
Date dataExp = new Date(hoje.getTime() + Long.parseLong(expiration));
return Jwts.builder().setIssuer("API do forum Alura")
.setSubject(user.getId().toString())
.setIssuedAt(hoje)
.setExpiration(dataExp)
.signWith(SignatureAlgorithm.HS256, secret)
.compact();
}
}
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.formDto.LoginForm;
@RestController
@RequestMapping("/auth")
public class AutenticacaoController {
@Autowired
private AuthenticationManager authManager;
private TokenService tokenService;
@PostMapping
public ResponseEntity<?> autenticar(@RequestBody @Valid LoginForm form){
UsernamePasswordAuthenticationToken dadosLogin = form.converter();
try {
Authentication auth = authManager.authenticate(dadosLogin);
String token = tokenService.gerarToken(auth);
System.out.println(token);
return ResponseEntity.ok().build();
} catch (AuthenticationException e) {
return ResponseEntity.badRequest().build();
}
}
}