# jwt
forum.jwt.expiration=86400000
forum.jwt.secret=rm'!@N=Ke!~p8VTA2ZRK~nMDQX5Uvm!m'D&]{@Vr?G;2?XhbC:Qa#9#eMLN\}x3?JR3.2zr~v)gYF^8\:8>:XfB:Ww75N/emt9Yj[bQMNCWwW\J?N,nvH.<2\.r~w]*e~vgak)X"v8H`MH/7"2E`,^k@n<vE-wD3g9JWPy;CrY*.Kd2_D])=><D?YhBaSua5hW%{2]_FVXzb9`8FH^b[X3jzVER&:jw2<=c38=>L/zBq`}C6tT*cCSVC^c]-L}&/
TokenService :
package br.com.alura.forum.config;
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;
@SuppressWarnings("deprecation")
public String gerarToken(Authentication authentication) {
Usuario logado = (Usuario) authentication.getPrincipal();
Date hoje = new Date();
Date dataExpiracao = new Date(hoje.getTime() + Long.parseLong(expiration));
return Jwts.builder()
.setIssuer("API do forúm da Alura")
.setSubject(logado.getId().toString())
.setIssuedAt(hoje)
.setExpiration(dataExpiracao)
.signWith(SignatureAlgorithm.HS256, secret)
.compact();
}
}
AutenticacaoController :
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.TokenService;
import br.com.alura.forum.controller.dto.LoginFormDto;
@RestController
@RequestMapping("/auth")
public class AutenticacaoController {
@Autowired
private AuthenticationManager authManager;
@Autowired
private TokenService tokenService;
@PostMapping
public ResponseEntity<?> autenticar(@RequestBody @Valid LoginFormDto form) {
UsernamePasswordAuthenticationToken dadosLogin = form.converter();
try {
Authentication authentication = authManager.authenticate(dadosLogin);
String token = tokenService.gerarToken(authentication);
System.out.println(token);
return ResponseEntity.ok().build();
} catch (AuthenticationException e) {
return ResponseEntity.badRequest().build();
}
}
}