Navigating to a new page using JWT authentication header in angularjs

I currently have a two-module AngularJS application. The first module is responsible for handling authentication processes such as login and register functionalities. The second module, known as "chat," is protected on the Node.js backend using the passport-jwt strategy. Each module has its own separate index.html file. In the authentication module, there is a register() method in the register controller that appears as follows:

$scope.register = function () {

         $http({
            method: 'post',
            url: '/api/register',
            data: {
                username: $scope.username,
                email: $scope.email,
                password: $scope.password
            },
            headers: {
                'Content-Type': 'application/json'
            }
        })

The route /api/register is responsible for all registration-related actions. Additionally, there is a login() method in the login controller which looks like this:

 $scope.login = function () {
            $http({
                method: 'post',
                url: '/api/login',
                data: {
                    username: $scope.username,
                    password: $scope.password
                },
                headers: {
                    'Content-Type': 'application/json'
                }
            }).then(function success(res) {
                //TODO redirect to '/chat' with auth token
            }
        };

If the user exists in the database, the API will return a JWT token accessible via res.body.token. This token should be utilized to retrieve the secure chat page available at the 'localhost:3000/chat' URL. However, I am facing difficulty in sending the proper request from the Angular client with an Authorization header containing the token to access the chat page.

Answer №1

To enhance the security of your HTTP requests, you can implement an HTTP interceptor that automatically adds a Bearer token to the request header:

// Set up an HTTP interceptor to handle adding the Bearer token for authorization
module.factory('bearerTokenInterceptor', function (BearerAuthService) {
  return {
    request: function (config) {      
      if (config.headers.Authorization === 'Bearer') {
        config.headers.Authorization = 'Bearer ' + btoa(BearerAuthService.getAccessToken());
      }
      return config;
    }
  };
});

module.config(function ($httpProvider) {
  $httpProvider.interceptors.push('bearerTokenInterceptor');
});

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

Using React and Material-UI: Implementing button functionality to call another class using hooks in the main App component

Just starting out with React/MUI and currently working on different components for a website, so the UI is not a priority at the moment. Encountering an issue when trying to create a button that links to the Sign Up page (similarly for Sign In): Error: ...

Is it possible to execute this animation with a single click for repetitive playback?

CODEPEN const btt = document.querySelector('.btt'); btt.addEventListener('click', function(){ this.classList.toggle('anime'); }); Is there a way to achieve the desired effect with just one click? ...

Mapping a dynamic URL to a static HTML document within a Java-based web application

I am currently working on a Java web app that is hosted in JBoss. The new feature I am adding is a job application page using AngularJS, and I want it to be responsive to the following (RESTful) URL: /job/<job id>/apply Being inexperienced with Ang ...

Removing background when an element is clicked can be achieved by using event listeners and CSS styles

As a newcomer to responsive design, I have a question about making the background color disappear when a SPAN element is clicked. Below is my code: HTML CODE <body> <span class="menu-trigger">MENU </span> <nav class = " ...

While attempting to utilize inner class functions in Node JS, an error is being encountered

I've been delving into Node JS and exploring how to implement an OOP structure within node. I've created a simple class where I'm using functions to verify and create users in a database. However, I'm encountering a TypeError when attem ...

I am facing difficulty in loading my services in AngularJS

I am reaching out for assistance with a recurring issue I have encountered while working with AngularJS. Throughout my coding education, the greatest challenge for me has always been linking files together. However, in AngularJS, this task has become parti ...

Using TypeScript to handle text resolution through the command line interface

Currently, I am developing a CLI application using TypeScript and employing enquirer for the purpose. More information about enquirer can be found here. In my project, I have a JSON object defined as follows: const person = { name: 'Mohan', ...

Transform all the string data to integers in the JSON reply

Apologies for the basic question: This is the response I'm receiving: {id: "bitcoin", name: "Bitcoin", symbol: "BTC", rank: "1", price_usd: "15487.0"} I want to convert rank: "1", price_usd: "15487.0" to rank: 1, price_usd: 15487.0 The reason beh ...

Callback function triggered upon the creation of a DOM node

I am in search of a way to have a specific callback function run each time a div that matches a particular selector is added to the DOM. I have explored the DOM events documentation and the event closest to what I need seems to be "load", however, it does ...

Using MUI Select with Array of Objects for values - Learn how to deselect a predefined state

I have a list of objects structured like this: [ { _id: "6311c197ec3dc8c083d6b632", name: "Safety" }, ........ ]; These objects are loaded as Menu Items options for my Select component: {categoryData && c ...

Ways to bypass a transition using JavaScript

Hello everyone, I would like to start by apologizing for any mistakes in my English. I have been working on a website, which is currently available here: As you scroll down, the height of the image below the menu decreases. I am trying to make the navig ...

Tips for Organizing an Array: Grouping Categories and Products

I have a single array and I am looking to separate categories from the products listed within it. const product = [{ id: 1, name: 'Cloth', cat: ['fashion', 'man', 'women'] }, { id: 2, name: &apos ...

Scrollbar not displaying in Chrome when using overflow-y: scroll

I'm currently creating a list of organizations on the left side of this page: To create this list, I am using <span> tags that are linked to the corresponding map. However, I'm facing an issue - the scroll bar doesn't show up in Chro ...

When using the 'rtl' direction in Dojo Text, all special characters are aligned to the right

I'm having an issue with keeping the text of a button centered followed by an icon. The code works fine until I add special characters in front of the button text. In that case, the special characters are placed after the text followed by the icon. I ...

Tips for assigning an event to a variable in JavaScript

Here is my javascript code snippet: function drag(ev){ var x= ev.dataTransfer.setData("Text",ev.target.id); } I am trying to pass a variable within this event so that I can perform a specific action. However, the current implementation is not worki ...

Is there a way to turn off the "swipe to navigate back" feature in Microsoft Edge using JavaScript or jQuery?

Working on a website that features horizontal object rotation. For instance, starting with the front view of an object followed by side, back, other side, and then back to the front. In this case, there are 24 images of an object, each taken at a 15 degre ...

Having trouble inserting JSON data into my PostgreSQL database using Node.js

Currently facing an issue while attempting to save JSON data into a database. This is the code I have: My service retrieves and caches data from an API with the specified parameter cep: const axios = require('axios'); const NodeCache = require(& ...

Exploring the textures of an imported 3D model mesh with multiple materials in A-Frame and Three JS

Currently, I am exploring A-Frame using a 3D model imported from Blender. Some parts of this model contain multiple meshes with two or more materials assigned to them. It is easy for me to adjust the material properties of meshes with just one material. ...

Verifying the Angular API Connection with Laravel

I've recently started working on a project using both Laravel and Angular. I have configured a route as shown below: Route::group(array('prefix' => 'api'), function() { Route::resource('getdealsbymerchant/{merchant_id} ...

Struggling to transfer information from JavaScript to Python Flask?

I am currently working on a basic configuration where I need to send a string to my Flask application through Ajax, but unfortunately, I am encountering Error code 400: Bad request. Here is the JavaScript code snippet: headers = { 'Content-type&a ...