我刚刚从Marionette.js转向角。现在我创建一个应用程序,其中有一个登录屏幕和主屏幕,我有身份验证双REST API的一个又一个一个检查,如果用户有活动的会话或没有(使用令牌)。如果用户有活动会话我想他重定向到主屏幕。
我怎样才能最好的方式实现这角?
谢谢,MSK
请注意:我使用的自耕农/发电机角和UI路由器
解决方案 验证服务\r\r
使用严格的;\r\rapp.factory('验证',功能验证($ HTTP,$饼干,$ Q){\r this.login = // ...\r this.isLoggedIn = // ...指向您的REST服务\r});
\r\r\r
通过UI路由器控制时进行身份验证需求\r\r
.STATE('设置',{\r 网址:/设置\r 验证:真//这其中,用户需要进行身份验证添加到状态\r });
\r\r\r
存储和检索标记\r\r
的app.config(函数($ httpProvider){\r //将拦截器添加认证头在服务器上验证\r $ httpProvider.interceptors.push('authInterceptor');\r })\r\rapp.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\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\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');
}
});
}
});