角身份验证和访问控制 [英] Angular Authentication and Access control
本文介绍了角身份验证和访问控制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我刚刚从Marionette.js转向角。现在我创建一个应用程序,其中有一个登录屏幕和主屏幕,我有身份验证双REST API的一个又一个一个检查,如果用户有活动的会话或没有(使用令牌)。如果用户有活动会话我想他重定向到主屏幕。
我怎样才能最好的方式实现这角?
谢谢,
MSK
请注意:我使用的自耕农/发电机角和UI路由器
解决方案
- 验证服务
\r
\r\r
\r 使用严格的;\r
\r
app.factory('验证',功能验证($ HTTP,$饼干,$ Q){\r
this.login = // ...\r
this.isLoggedIn = // ...指向您的REST服务\r
});
\r
<醇开始=2>
\r
\r\r
\r .STATE('设置',{\r
网址:/设置\r
验证:真//这其中,用户需要进行身份验证添加到状态\r
});
\r
<醇开始=3>
\r
\r\r
\r 的app.config(函数($ httpProvider){\r
//将拦截器添加认证头在服务器上验证\r
$ httpProvider.interceptors.push('authInterceptor');\r
})\r
\r
app.factory('authInterceptor',函数($饼干){\r
VAR状态;\r
返回{\r
//授权令牌添加到页眉\r
要求:功能(配置){\r
config.headers = config.headers || {};\r
如果($ cookies.get('令牌')){\r
config.headers.Authorization ='承载'+ $ cookies.get('令牌');\r
}\r
返回配置;\r
}\r
};\r
});
\r
<醇开始=4>
\r
\r\r
\r app.run(函数($ rootScope,$状态,验证){\r
//重定向到登录路线是否需要身份验证\r
$ rootScope。在$('$ stateChangeStart',函数(事件,旁边){\r
如果(next.authenticate){\r
Auth.isLoggedIn(功能(的loggedIn){\r
如果(!的loggedIn){\r
。事件preventDefault();\r
$ state.go('登录');\r
}\r
});\r
}\r
});
\r
I have just shifted from Marionette.js to Angular. Right now I am creating one application where there is a login screen and home screen, I have two rest apis one for authentication and another one to check if user has active session or not(using tokens). If user has active session I want to redirect him to home screen.
How can I implement this in Angular in best way?
Thanks, MSK
Note: I am using yeoman/generator-angular and ui-router
解决方案
- Authentication service
'use strict';
app.factory('Auth', function Auth($http, $cookies, $q) {
this.login = //...
this.isLoggedIn = //... point to your REST services
});
- Controlling through ui-router when needs to be authenticated
.state('settings', {
url: '/settings',
authenticate: true //add this to state where user needs to be authenticated
});
- Storing and retrieving tokens
app.config(function($httpProvider) {
//add interceptor to add authentication header to be verified on the server
$httpProvider.interceptors.push('authInterceptor');
})
app.factory('authInterceptor', function($cookies) {
var state;
return {
// Add authorization token to headers
request: function(config) {
config.headers = config.headers || {};
if ($cookies.get('token')) {
config.headers.Authorization = 'Bearer ' + $cookies.get('token');
}
return config;
}
};
});
- Checking certain states and redirecting if needed
app.run(function($rootScope, $state, Auth) {
// Redirect to login if route requires authentication
$rootScope.$on('$stateChangeStart', function(event, next) {
if (next.authenticate) {
Auth.isLoggedIn(function(loggedIn) {
if (!loggedIn) {
event.preventDefault();
$state.go('login');
}
});
}
});
这篇关于角身份验证和访问控制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文