Ao compilar me é retornado o seguinte erro:
APPLICATION FAILED TO START
Description:
Field tokenService in br.com.alura.forum.controller.AutenticacaoController required a bean of type 'br.com.alura.forum.config.security.TokenService' that could not be found.
The injection point has the following annotations:
- @org.springframework.beans.factory.annotation.Autowired(required=true)
Action:
Consider defining a bean of type 'br.com.alura.forum.config.security.TokenService' in your configuration.
Process finished with exit code 0
Porém na classe controller está tudo ok:
package br.com.alura.forum.controller;
import br.com.alura.forum.config.security.TokenService; import br.com.alura.forum.controller.form.LoginForm; 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 javax.validation.Valid;
@RestController @RequestMapping("/auth") public class AutenticacaoController {
@Autowired
private AuthenticationManager authManager;
@Autowired
private TokenService tokenService;
@PostMapping
public ResponseEntity<?> auntenticar(@RequestBody @Valid LoginForm form){
UsernamePasswordAuthenticationToken dadosLogin = form.converte();
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();
}
}
}
Classe TokenService:
package br.com.alura.forum.config.security;
import br.com.alura.forum.modelo.Usuario; import io.jsonwebtoken.Jwts; import io.jsonwebtoken.SignatureAlgorithm; import org.springframework.beans.factory.annotation.Value; import org.springframework.security.core.Authentication;
import java.util.Date;
public class TokenService {
@Value("${forum.jwt.expiration")
private String expiration;
@Value("${forum.jwt.secret")
private String secret;
public String gerarToken(Authentication authentication){
Usuario logado = (Usuario) authentication.getPrincipal(); //Isso recupera o usário logado
Date hoje = new Date();
Date dataExpiracao = new Date(hoje.getTime() + Long.parseLong(expiration));
return Jwts.builder()
.setIssuer("API do Fórum da Alura") //Nome da aplicação que está gerando o token
.setSubject(logado.getId().toString()) //Nome do usuário logado
.setIssuedAt(hoje)
.setExpiration(dataExpiracao)
.signWith(SignatureAlgorithm.HS256, secret)
.compact();
}
}