简体   繁体   English

AngularJS使用restful api进行身份验证,成功时返回令牌

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

I'm working with a restful API that when authenticating a user successfully, the request returns a token. 我正在使用一个restful API,在成功验证用户时,请求返回一个令牌。 The token is then added as a header on every request like this: 然后将令牌添加为每个请求的标头,如下所示:

Authorization: Bearer <token>

I struggled to find a good way to do authentication without a lot of code bloat. 我很难找到一种很好的方法来进行身份验证,而不需要很多代码膨胀。

I came up with a good solution using HTML5 sessionStorage. 我想出了一个使用HTML5 sessionStorage的好解决方案。 Here's a simple example: 这是一个简单的例子:

// 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