Boa noite pessoal, estou com uma dúvida que não consigo sanar
tenho uma aplicação java.
na tela de Login eu realizo uma autenticação no banco de dados e retorno um token de acesso, faço essa autenticação pegando o login e senha e verificando no banco de dados se o usuario existe se existir eu retorno um token no cookie do navegador.
tenho um filter para a url /cliente, toda vez que for acessala será necessario passar o token:
Meu filter
package com.alonsegal.multitenancy;
import java.util.Base64;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import com.alonsegal.repository.AdminRepository;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureException;
@Component
public class TenantInterceptor extends HandlerInterceptorAdapter {
@Value("${jwt.header}")
private String tokenHeader;
@Value("${jwt.secret}")
private String tokenSecret;
@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(Base64.getEncoder().encodeToString(tokenSecret.getBytes())).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();
}
}
O problema é que mesmo autenticando eu não consigo redirecionar para outra pagina e sempre fica na pagina de login, o meu Controller de cliente ta assim:
package com.alonsegal.controller;
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.CacheControl;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import com.alonsegal.domain.Cliente;
import com.alonsegal.service.ClienteService;
import com.alonsegal.utils.NegocioException;
@Controller
@RequestMapping("/cliente")
public class ClienteController {
@Autowired
private ClienteService service;
@RequestMapping(method=RequestMethod.POST)
public String salvar(@RequestBody Cliente cliente){
try {
this.service.salvar(cliente);
} catch (NegocioException e) {
e.printStackTrace();
}
return "cadastroClientes";
}
@RequestMapping(value="/{id}", method=RequestMethod.DELETE)
public ResponseEntity<Cliente> deletar(@RequestBody Cliente cliente, @PathVariable("id") Long codigo){
cliente.setCodigoCliente(codigo);
cliente.setIsAtivo(false);
try {
this.service.deletar(cliente);
} catch (NegocioException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return ResponseEntity.status(HttpStatus.OK).build();
}
@RequestMapping(value="/{id}", method=RequestMethod.PUT)
public ResponseEntity<Cliente> atualizar(@RequestBody Cliente cliente, @PathVariable("id") Long codigo){
try {
this.service.atualizar(cliente);
} catch (NegocioException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return ResponseEntity.status(HttpStatus.OK).build();
}
@RequestMapping(value="/{id}", method=RequestMethod.GET)
public ResponseEntity<?> buscarCliente(@PathVariable("id") Long codigo){
Cliente cliente = null;
try {
cliente = this.service.buscarCliente(codigo);
} catch (NegocioException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
@SuppressWarnings("unused")
CacheControl cache = CacheControl.maxAge(20, TimeUnit.SECONDS);
return ResponseEntity.status(HttpStatus.OK).body(cliente);
}
@RequestMapping(method=RequestMethod.GET)
public String buscarClientes(){
return "listClientes";
}
}
na minha chamada ajax faço isso aqui:
arquivo js
$(function(){
enviar();
});//init
var auth = {};
var Authorization;
var token;
var enviar = function(){
$('form').submit(function(e){
e.preventDefault();
componentInteraction();
$.ajax({
type : 'POST',
url : 'auth',
contentType: 'application/json',
data : JSON.stringify(auth),
success : function(){
alert('logi realizado consucesso');
//aqui eu tento redireioncar para a url /cliente, porem a url não muda
callPageListClientes();
},
error : function(error){
console.dir(error);
}
});
});
};
var componentInteraction = function(){
var email = $('#inputEmail').val();
var passWord = $('#inputPassword').val();
auth.email = email;
auth.passWord = passWord;
};
var callPageListClientes = function(){
$.ajax({
type : 'GET',
url : 'cliente',
contentType: 'application/json',
success : function(){
alert('realizado com sucesso');
},
error : function(error){
alert(error);
},
beforeSend: function(xhr){
getCookie();
xhr.setRequestHeader(Authorization, token);
xhr.setRequestHeader('contentType', 'application/json');
}
});
};
var getCookie = function(){
cookie = document.cookie;
var split = cookie.split('=');
Authorization = split[0];
token = 'Bearer ' + split[1];
};