Angular Authentication and Access control

2019-05-22 17:39发布

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条回答
做自己的国王
2楼-- · 2019-05-22 18:21
  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');
          }
        });
      }
    });

查看更多
登录 后发表回答