Block navigation until token login is validated, using Spring, Angularjs and Javascript

Asked

Viewed 383 times

1

I have a question.. I have implemented a login validation using JWT. It works all right, generates the token within the requests. However, on the login page, if in the URL I put the next page the system lets go.

Login Controller

@RestController
public class LoginController {

    @Autowired
    private EntidadesAdministradoresService eaService;

    @RequestMapping(value = "/autenticar", consumes = MediaType.APPLICATION_JSON_VALUE, method = RequestMethod.POST)
    public LoginResponse autenticar(@RequestBody Entidades_administradores entidadesAdministradores) throws ServletException {

        //verifica se foram digitados o login e senha no front end
        if (entidadesAdministradores.getUsuario_administrador() == null
                || entidadesAdministradores.getSenha_administrador() == null) {
            throw new ServletException("Nome ou senha obrigatório");
        }

        // busca no banco de dados
        Entidades_administradores entAdministradoresAutenticado = eaService
                .buscarPorNome(entidadesAdministradores.getUsuario_administrador());

        if (entAdministradoresAutenticado == null) {
            throw new ServletException("Usuário não encontrado");
        }

        // compara a senha vinda do banco de dados com a senha vinda da tela
        if (!entAdministradoresAutenticado.getSenha_administrador()
                .equals(entidadesAdministradores.getSenha_administrador())) {
            throw new ServletException(" Senha inválida");
        }

        String token = Jwts.builder().setSubject(entAdministradoresAutenticado.getUsuario_administrador())
                .signWith(SignatureAlgorithm.HS512, "digi2fred")
                .setExpiration(new Date(System.currentTimeMillis() + 1 * 60 * 1000)).compact();

        return new LoginResponse(token); 
    }

    private class LoginResponse {
        public String token;

        public LoginResponse(String token) {
            this.token = token;
        }

        public String getToken() {
            return token;
        }  
    }    
}

Requestmapping

public class HomeController {
    @RequestMapping("/home")
    public String irParaHome(){

        return "home";
    }

    @RequestMapping("/login")
    public String irParaLogin(){

        return "login";
    }

    @RequestMapping("/escolherSistema")
    public String irParaEscolherSistema(){
        return "escolherSistema";
    }

    @RequestMapping("/inicio")
    public String irParainicio(){
        return "inicio";
    }

    @RequestMapping("/saude")
    public String irParaSaude(){
        return "saude";
    } 

    @RequestMapping("/localTrabalho")
    public String irParalocalTrabalho(){
        return "localTrabalho";
    } 

} 

LoginCOntroller.js

app.controller("loginController", function($scope, $http, $location) {
    $scope.entidadesAdministradores = {};
    $scope.token = ""; 

    $scope.autenticar = function() {

        $http.post("/autenticar", $scope.entidadesAdministradores).then(
                function(response) {
                    $scope.token = response.data.token;
                    localStorage.setItem("userToken", response.data.token);
                    $location.path("/home"); // alterei
                    window.location.reload(true); // alterei
                },

                function(response) {
                    console.log(response);

                });

    };

});

1 answer

0


One solution I found was to make a Java command in the home.js file

if(localStorage.getItem("userToken")==null){
        $q.when();
        $location.path("/login");
        window.location.reload(true);
    } 

When someone tries to make a request via http to the home page the command checks if there is a token, if there is no token it goes back to the login page.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.