问题描述
问题是,如果用户没有有效的JWT,我想限制对特定路由的访问并显示登录页面。我只是想告诉我,我在AngularJ和NodeJ中是非常新的。简而言之,我有
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:
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;
});
}
我引发了一个事件,在ApplicationCtrl中事件被该事件捕获
I rise an event, in ApplicationCtrl the event is catched by this
$scope.$on('login', function(_, user){
$scope.currentUser = user
})
这很酷,而且运行完美,问题在于我有一些路线我想对我的route.js进行验证。
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'});
在nodejs中,我可以轻松地放置中间件,但是如何在AngularJs中做到这一点。所以现在发生的是,当我进入页面时,我可以按登录。它会将我重定向到登录页面,然后当我按Posts时,Nodejs返回401,因为我没有有效的JWT,但这仅显示在控制台中。
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.
推荐答案
@SayusiAndo指出您需要:
As @SayusiAndo pointed out you need :
- 从您的节点服务器捕获401状态。
- ,然后将用户重定向到/ login路由(如果未登录)。
- 此外,您还应该发送jwt令牌(应存储),使用相同的拦截器。
- 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拦截器:
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');
});
这篇关于AngularJs路由认证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!