Securing access to AngularJS applications using a restful API that generates a token upon successful authentication

Currently, I am integrating a restful API which issues a token when authenticating a user successfully. This token needs to be included as a header in every subsequent request in the following format:

Authorization: Bearer <token>

I found it challenging to implement authentication without adding excessive amounts of code.

Answer №1

Utilizing the power of HTML5 sessionStorage, I was able to devise an effective solution. Take a look at this straightforward illustration:

// Initializing the main module
var myapp = angular.module('myapp', []);
// Defining actions to be executed when running the application
myapp.run(['$location', '$rootScope',
  function($location, $rootScope) {
    // Setting up a listener to monitor route changes. This ensures that a user is logged in before accessing data.
    $rootScope.$on("$routeChangeStart", function(event, next, current) {
      // Checking if there is no token, indicating that the user is not logged in
      if (sessionStorage.getItem("token") === null) {
        // Redirecting to the login page
        window.location.href = "login.html";
      }
    });
}]);
// Creating a controller for the login page
myapp.controller('LoginController', ['$scope', '$http',
  function($scope, $http) {
    // Automatically filling in email/password fields if user had selected "remember me"
    // Login functionality triggered upon form submission
    $scope.login = function() {
      // Authenticating the user by sending a POST request to the server. Upon successful authentication, a token is received.
      $http.post('http://example.com/login', $scope.user)
        .success(function(response) {
          // Storing the token in sessionStorage under the key "token"
          sessionStorage.setItem("token", response.token);
          // Redirecting to the desired location
          window.location = 'index.html';
        });
    };
}]);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is it achievable to utilize a watch in the filtering feature of AngularJS?

I am looking to enhance a filter function that is responsible for enabling or disabling a button. Within my code, I have an array and I receive a variable called (serviceVariable) from a service. I iterate through this array to determine if the service va ...

Resolve Redux-Firestore issue #45: Possible Solutions?

I'm facing an issue where deleting a document from Firestore results in my Redux store showing it as null instead of removing it. Even though the document is deleted in Firestore, this inconsistency causes frontend issues because my .map functions can ...

Utilize a WebGLRenderTarget in a recursive manner with the power of threejs and GLSL programming

As a newcomer to both ThreeJS and GLSL, I am exploring ways to reuse the output of a fragment shader in another shader, while also utilizing that same output in the subsequent frame of the same shader. Essentially, the output of the shader is dependent on ...

Tips for verifying if a specific key value is present in JSON data received from the backend in an Angular application

Within my angular application, I successfully retrieved the data from the server in JSON format. Here is an example of the JSON data: jsondata = { Id: 16531914, EmailId: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfe ...

Is there an alternative if statement with 3 or more conditions?

I've been attempting to solve this issue for quite some time now, but I just can't seem to pinpoint what exactly I'm doing incorrectly. The first two conditions appear to be functioning properly, but the third one is failing to execute as ex ...

What is the best way to pass template variables in Meteor?

I couldn't find a solution for this particular issue, although I have encountered it in the past. The challenge is to render a template with a variable set from HTML and also be able to access it in JavaScript. Here's a straightforward example t ...

Running a command once the forEach loop is completed in Angular

Within the HTML, I have a function that is triggered by an ng-click: vm.items = []; vm.moveItems = function() { angular.forEach(vm.items, function (item) { $http({ method: 'PUT', url: &apos ...

I am looking for a regular expression that will eliminate any leading white space while still permitting spaces between words

Below is the code I've created for an angularjs directive that removes spaces. It successfully eliminates spaces between words, but unfortunately still allows leading spaces. function customValidation() { return { require: 'ngModel&apos ...

What is the best way to transfer data from a fully filled out JSON form to a PHP database

Is there a way to automatically send a completed JSON form when the device detects an internet connection? I am facing the challenge of dynamically generated IDs for each question and need to figure out how to submit the data to the database on button cl ...

How to prevent click events and still enable scrolling within a DIV using CSS/JS

Basically, I am looking to enable scrolling within a DIV while also disabling click events. Any suggestions on how this can be achieved? Appreciate any help! ...

I need help figuring out how to create dynamic bars that change colors based on their values. Any suggestions on how to

Seeking a solution to create interactive live-charts similar to the image provided. I've explored various chart libraries like Highcharts, fusioncharts, raphaeljs and many others, but haven't found one that fits my needs perfectly. I experimented ...

Changing the structure of elements in an array using JavaScript

I am seeking a way to convert an array of strings, which represent dates in the format of 201001 ,201002, into something more readable like 2010 January, 2010 February. Do you have any suggestions on how to achieve this? var Array = ["201005", "201006", " ...

Creating specialized paths for API - URL handlers to manage nested resources

When working with two resources, employees and employee groups, I aim to create a structured URL format as follows: GET /employees List employees. GET /employees/123 Get employee 123. GET /employees/groups List employee groups. GET /employees/groups/123 ...

Node.js routing issues leading to rendering failures

I have been working on a website that involves carpooling with drivers and passengers. When a driver submits their details, they are directed to a URL where they can select the passenger they want to ride with. Here is the code snippet I have written: ap ...

Dividing an Image into segments using Javascript

I'm currently working on a basic Jigsaw puzzle project. To achieve this, I am required to divide the image I've selected into 20 separate pieces. I was wondering if there is a method in Javascript that can automatically cut an image into 20 equal ...

Incorporating SAML (SSO) into an Angular website for seamless integration

My website is built with AngularJS on the frontend and Python on the backend. Currently, we are using a basic webform to collect user credentials. The form data is then sent to our Python backend (using Flask as a webservice) for authentication. Now, we ...

Filling out the form will automatically direct you to the text input section

I'm trying to figure out if I can create an input box in HTML that directs the user to a specific HTML file based on the word they enter. For example, if they type "Doctor", it would redirect them to the page doctor.html. This is for a school project ...

Sending data between controllers in AngularJS

As a newcomer to Angular, I am facing challenges in understanding how to utilize a Service to transfer data from one controller to another. My experience with Angular so far has involved successfully calling controllers and passing data to them from withi ...

The issue with Angular's read-only rating stars not displaying the server-passed value

I'm currently using angular ui-bootstrap rating stars to display static values passed through a django-python controller via a $http get request. These values are being shown inside a table, but for some reason, the data I've passed is not displa ...

I encounter difficulty utilizing assets within my React application

Currently, I am in the process of developing a React application for practice purposes. However, I have encountered an issue with using images and audio files stored in the assets folder. Despite my attempts to import them into the project, I have been uns ...