Federico Giaccari
Federico Giaccari

Reputation: 75

Angular and JWT, redirect after authentication

I'm able to make the authentication using JWT and angular-jwt, but now how can i redirect the user to the home page including the token in the header request? I'm using Spring Boot for the server side and i'd like to know how to serve this request.

Upvotes: 1

Views: 1298

Answers (1)

Mehdi
Mehdi

Reputation: 578

this is the front-end's responsibility, you should redirect the user from angular, you can use the $location service. as to the token you can store it in the $rootScope or in a client side cookie, here is an example of a jwt auth service i have wrote before it uses the $rootScope to store the client state. note that this is not a production code.

app.service('AuthService', function ($rootScope, $http, $location) {
    var service = this;
    service.authenticate = function (credentials) {
        $http({
            'url': authUrl,
            'method': 'POST',
            'headers': {'Content-Type': 'application/json'},
            'data': credentials
        }).then(function (response) {
            if (response.data.token && response.data.token.length > 0) {
                $rootScope.authenticated = true;
                $rootScope.jwtToken = response.data.token;
                $location.path('/home');
            } else {
                $rootScope.logout();
            }
        }, function () {
            $rootScope.logout();
        });

        $rootScope.logout = service.logout;
    };

    service.isAuthenticated = function () {
        return $rootScope.authenticated;
    };

    service.logout = function () {
        $rootScope.authenticated = false;
        $rootScope.jwtToken = null;
    };
});

Upvotes: 1

Related Questions