0

I'm working with a restful API that when authenticating a user successfully, the request returns a token. 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.

1 Answer 1

2

I came up with a good solution using 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';
        });
    };
}]);
Sign up to request clarification or add additional context in comments.

3 Comments

one security concern would be can users access anything with script disabled on index page
It's not a security concern because all of the requests for data come from http requests just as the authentication. So if JS is disabled, you can't get data anyways.
assumed the data part, which is almost a given in angular.. just passing along a thought is all...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.