AngularJs route authentication

做~自己de王妃 提交于 2019-12-25 14:05:50

问题


The problem is that I would like to restrict access to specific routes and show login page if user does not have valid JWT. I just wanna tell that I'm very new in AngularJs and NodeJs. So in short I have

LoginCtrl:

$scope.login = function(username, password){

UserSvc.login(username, password)
.then(function(response){
    $scope.$emit('login', response.data );
    $window.location.href = '#/';
}, function(resp){
    $scope.loginError = resp.data.errors;
});     
}

I rise an event, in ApplicationCtrl the event is catched by this

$scope.$on('login', function(_, user){
    $scope.currentUser = user
})

Which is cool and it's working perfect, the problem is that I have some routes in my route.js, on which I would like to have some validation.

$routeProvider
.when('/', {controller:'PostsCtrl', templateUrl: 'posts.html'})
.when('/register', {controller:'RegisterCtrl', templateUrl: 'register.html'} )
.when('/login', {controller:'LoginCtrl', templateUrl: 'login.html'} )
.otherwise({redirectTo: '/login'});

In nodejs I can easy put a middleware, but how can I do that in AngularJs. So now what's is happening is that when I land on the page I can press login. It's redirects me to login page, then When I press Posts, Nodejs returns 401 because I don't have valid JWT, but that is shown only in the console. AngulrJs doesn't do anything.


回答1:


As @SayusiAndo pointed out you need :

  • http interceptor that will catch the 401 status, from you node server.
  • and, then redirect the user to /login route if not logged in.
  • Also, you should send your jwt token (that you should store), using the same interceptor.

Http interceptor :

app.factory('AuthInterceptor', function ($window, $q) {
return {
    request: function(config) {
        var token = $window.localStorage.getItem('token');
        if(token){
            config.headers.Authorization = 'Bearer ' + token;
        }

        return config;
    },
    response: function(response) {
        if (response.status === 401) {
            // redirect to login.
        }
        return response || $q.when(response);
    }
};
});

// Register the AuthInterceptor.
app.config(function ($httpProvider) {
    $httpProvider.interceptors.push('AuthInterceptor');
});



回答2:


You can use $routeChangeStart event which is fired every time angular enters a route. Attach a handler to this event and in the handler do the validation you need to and if it fails, redirect user.

https://docs.angularjs.org/api/ngRoute/service/$route



来源:https://stackoverflow.com/questions/32679348/angularjs-route-authentication

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!