简体   繁体   English

AngularJs路由认证

[英]AngularJs route authentication

The problem is that I would like to restrict access to specific routes and show login page if user does not have valid JWT. 问题是,如果用户没有有效的JWT,我想限制对特定路由的访问并显示登录页面。 I just wanna tell that I'm very new in AngularJs and NodeJs. 我只想告诉我,我在AngularJ和NodeJ中是非常新的。 So in short I have 总之我有

LoginCtrl: 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 我引发一个事件,在ApplicationCtrl中该事件被捕获

$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. 这很酷,并且可以完美地工作,问题是我的route.js中有一些路由,我希望对其进行验证。

$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. 在nodejs中,我可以轻松地放置中间件,但是如何在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. 它会将我重定向到登录页面,然后当我按Posts时,Nodejs返回401,因为我没有有效的JWT,但这仅在控制台中显示。 AngulrJs doesn't do anything. AngulrJs不会做任何事情。

As @SayusiAndo pointed out you need : 正如@SayusiAndo指出的那样,您需要:

  • http interceptor that will catch the 401 status, from you node server. 从节点服务器捕获401状态的http拦截器
  • and, then redirect the user to /login route if not logged in. 然后将用户重定向到/ login路由(如果尚未登录)。
  • Also, you should send your jwt token (that you should store), using the same interceptor. 另外,您应该使用相同的拦截器发送jwt令牌(应存储)。

Http interceptor : Http拦截器:

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');
});

You can use $routeChangeStart event which is fired every time angular enters a route. 您可以使用$ routeChangeStart事件,该事件在angular每次输入路线时都会触发。 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://docs.angularjs.org/api/ngRoute/service/ $ route

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM