Angular Authentication and Access control

半世苍凉 提交于 2019-12-22 11:37:52

问题


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:


  1. Authentication service

'use strict';

app.factory('Auth', function Auth($http, $cookies, $q) {
    this.login = //...
    this.isLoggedIn = //... point to your REST services
});
  1. 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
      });
  1. 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;
      }
    };
});
  1. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!