簡體   English   中英

AngularJS使用restful api進行身份驗證,成功時返回令牌

[英]AngularJS Authentication with a restful api that returns a token on success

我正在使用一個restful API,在成功驗證用戶時,請求返回一個令牌。 然后將令牌添加為每個請求的標頭,如下所示:

Authorization: Bearer <token>

我很難找到一種很好的方法來進行身份驗證,而不需要很多代碼膨脹。

我想出了一個使用HTML5 sessionStorage的好解決方案。 這是一個簡單的例子:

// Main module declaration
var myapp = angular.module('myapp', []);
// Set some actions to be performed when running the app
myapp.run(['$location', '$rootScope',
  function($location, $rootScope) {
    // Register listener to watch route changes.We use this to make 
    // sure a user is logged in when they try to retrieve data
    $rootScope.$on("$routeChangeStart", function(event, next, current) {
      // If there is no token, that means the user is not logged in
      if (sessionStorage.getItem("token") === null) {
        // Redirect to login page
        window.location.href = "login.html";
      }
    });
}]);
// A controller for the login page
myapp.controller('LoginController', ['$scope', '$http',
  function($scope, $http) {
    // If a user has check the "remember me" box previously and the email/pass
    // is in localStorage, set the email/password
    // Login method when the form is submitted
    $scope.login = function() {
      // Authenticate the user - send a restful post request to the server
      // and if the user is authenticated successfully, a token is returned
      $http.post('http://example.com/login', $scope.user)
        .success(function(response) {
          // Set a sessionStorage item we're calling "token"
          sessionStorage.setItem("token", response.token);
          // Redirect to wherever you want to
          window.location = 'index.html';
        });
    };
}]);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM