问题
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
回答1:
- 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');
}
});
}
});
来源:https://stackoverflow.com/questions/34646967/angular-authentication-and-access-control