Bom dia, pessoal estou com uma dúvida numa api que estou fazendo pro meu TCC,
é uma API REST feito com spring, nela tenho uma rota de autenticação que verifica se o usuario existe na base de dados e se existir um token e gerado para aquele usuario, usei a especificação JWT para gerar o token.
Classe de autenticacao
@RestController
public class AuthController {
@Autowired
private TenantNameFetcher tenantResolver;
@Value("${jwt.header}")
private String tokenHeader;
private String jwtToken;
@Autowired
private AuthService service;
@RequestMapping(value = "/auth", method = RequestMethod.POST)
public ResponseEntity<TokenUtil> auth(@RequestBody Admin admin, HttpServletResponse response) throws NegocioException, IOException {
//verifica se email e senha são válidos
service.autentica(admin);
try {
//recupera a empresa atraves do email
tenantResolver.setUsername(admin.getEmail());
ExecutorService es = Executors.newSingleThreadExecutor();
Future<UserTenantRelation> utrFuture = es.submit(tenantResolver);
UserTenantRelation utr = utrFuture.get();
es.shutdown();
TenantContext.setCurrentTenant(utr.getTenant());
} catch (Exception e) {
e.printStackTrace();
}
//gera o token apartir do login, passando a chave
jwtToken = Jwts.builder().setSubject(admin.getEmail()).signWith(SignatureAlgorithm.HS256, "minha key secreta").compact();
System.out.print("secret auth: " + jwtToken);
//Generate JWT for user and send it as a Secured & HttpOnly cookie
Cookie cookie = new Cookie(tokenHeader, jwtToken);
cookie.setPath("/");
cookie.setMaxAge(5000);
response.addCookie(cookie);
return ResponseEntity.status(HttpStatus.OK).body(new TokenUtil(jwtToken));
}
private class TokenUtil{
public TokenUtil(String token){
this.token = token;
}
private String token;
public String getToken(){
return this.token;
}
}
}
Toda vez que alguém acessa umas das rotas mapeadas na minha api pego o Authentication no cabeçalho da requisição.
@Component
public class TenantInterceptor extends HandlerInterceptorAdapter {
@Value("${jwt.header}")
private String tokenHeader;
@Autowired
private AdminRepository repository;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
String authToken = request.getHeader(this.tokenHeader);
String tenantId = null;
if (authToken == null || !authToken.startsWith("Bearer "))
throw new ServletException("Cabeçalho de Atorização inválido!");
String token = authToken.substring(7);
try{
String login = Jwts.parser().setSigningKey("minha key secreta").parseClaimsJws(token).getBody().getSubject();
tenantId = this.repository.getEmpresa(login);
}catch(SignatureException e){
throw new ServletException("Token Inválido ou Inexistente");
}
TenantContext.setCurrentTenant(tenantId);
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
ModelAndView modelAndView) throws Exception {
TenantContext.clear();
}
}
caso não de nenhuma exception o usuario é liberado e ele procede pro recurso solicitado.
Sei que faço isso atraves de token, mas qual a diferença de Oath não consigo diferenciar um de outro, caso tenha que usar Oath como ficaria?
Agradeço desde já pela explicação.