Description:
Field authManager in br.com.alura.forum.controller.AutenticacaoController required a bean of type 'org.springframework.security.authentication.AuthenticationManager' 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 'org.springframework.security.authentication.AuthenticationManager' in your configuration.
Classe Token Service
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 authentication) {
Usuario logado = (Usuario) authentication.getPrincipal();
Date hoje = new Date();
Date dataExpiracao = new Date(hoje.getTime() + expiration);
return Jwts.builder()
.setIssuer("API do Fórum da Alura")
.setSubject(logado.getId().toString())
.setIssuedAt(hoje)
.setExpiration(hoje)
.signWith(SignatureAlgorithm.HS256, secret)
.compact();
}
}
Classe 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.security.TokenService; import br.com.alura.forum.controller.form.LoginForm;
@RestController @RequestMapping("/auth") public class AutenticacaoController {
@Autowired
private AuthenticationManager authManager;
@Autowired
private TokenService tokenService;
@PostMapping
public ResponseEntity<?> autenticar(@RequestBody @Valid LoginForm 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();
}
}
}