Sending auth0 token as a parameter in $http.get request in Angular

I am encountering difficulties when trying to attach the auth0 token to a http.get request for an API that requires the token. The token is generated upon user login and stored in the browser's local storage, which is functioning properly. The challenge lies in appending the token to the http.get request.

Here is the code I currently have. In my app.js:

var QuoteApp = angular.module('QuoteApp', ['ui.router', 'auth0', 'angular-jwt', 'angular-storage', 'ngCookies']);
priceQuoteApp.config(function ($stateProvider, $urlRouterProvider, $httpProvider, authProvider, $locationProvider, jwtInterceptorProvider) {

jwtInterceptorProvider.tokenGetter = function(store, jwtHelper, auth) {
    var idToken = store.get('token');
    var refreshToken = store.get('refreshToken');
    if (!idToken || !refreshToken) {
        return null;
    }        
}
$httpProvider.interceptors.push('jwtInterceptor');

});

Furthermore, I have a $http.get function sending a request to the API requiring the token.

In my api.service.js file:

this.getStuff = function (attributes) {
    return $http.get('http://www.theurl.com/api/getstuff?json=' + JSON.stringify(attributes)).
        success(function(){
        });
};

The getStuff function is called from my getStuff.js file as follows:

$scope.getTheStuff = function (){
         Services.getStuff($scope.Attributes)
         .then(function (res) {
         })
    };

Upon making the request, I receive an authentication error from the server - 401 (Unauthorized), indicating that the token did not append to the http.get request. Any insights into this issue?

I have also provided the headers from the browser console below:

Remote Address:10.34.51.34:80
Request URL:http://www.theurl.com/api/getstuff?json={stuff in here}]}
Request Method:GET
Status Code:401 Unauthorized
Accept:application/json, text/plain, */*
Accept-Encoding:gzip, deflate, sdch
Host:http://www.theurl.com
Origin:http://localhost:63342
Referer:http://localhost:63342/price-tool-ui-1/app/index.html
User-Agent:Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.115 Safari/537.36
Access-Control-Allow-Methods:GET, POST, OPTIONS, PUT, DELETE
Access-Control-Allow-Origin:*

Answer №1

Make sure you are properly handling the token in

jwtInterceptorProvider.tokenGetter
. Check out more information in the documentation

jwtInterceptorProvider.tokenGetter = function(store, $http, jwtHelper) {
  var idToken = store.get('token');
  var refreshToken = store.get('refreshToken');
  if (jwtHelper.isTokenExpired(idToken)) {
    return auth.refreshIdToken(refreshToken);
  } else {
    return idToken;
  }
}

Answer №2

Make sure you remember to return the token retrieved from localStorage.

@eer made a good point in their response, but it's important to save the newly refreshed token to avoid calling the same endpoint again next time.

Here is an example of what the code should look like:

var refreshingToken = null;
jwtInterceptorProvider.tokenGetter = function(store, $http, jwtHelper) {
  var token = store.get('token');
  var refreshToken = store.get('refreshToken');
  if (token) {
    if (!jwtHelper.isTokenExpired(token)) {
      return store.get('token');
    } else {
      if (refreshingToken === null) {
        refreshingToken =  auth.refreshIdToken(refreshToken).then(function(idToken) {
          store.set('token', idToken);
          return idToken;
        }).finally(function() {
            refreshingToken = null;
        });
      }
      return refreshingToken;
    }
  }
}

I hope this explanation helps!

For more information, check out https://github.com/auth0/auth0-angular/blob/master/docs/refresh-token.md

Thank you!

Answer №3

It seems like there might be a misunderstanding about your issue. However, here is my method for including the token in the http request to interact with my API after authentication:

$http.defaults.headers.common['token'] = token;

The specific header name will vary depending on what your API requires (it could be X-Auth, Token, X-Token, etc.).

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

AngularJS: The blend of bo-bind, bindonce, and the translate filter

I am currently working with angular 1.2.25, angular-translate 2.0.1, angular-translate-loader-static-files 2.0.0, and angular-bindonce 0.3.1. My goal is to translate a static key using bindonce. Here is the code snippet I have: <div bindonce> < ...

Here's a guide on how to display texts underneath icons in Buttons using Material UI

Currently, this is the Button I have displayed https://i.sstatic.net/YkHp0.png I am trying to figure out how to position the Dummy Button text beneath the icon. Can someone assist me with this? Below is my code snippet: <Button className={classes.d ...

Retrieve the Object from the array if the input value is found within a nested Array of objects

Below is the nested array of objects I am currently working with: let arrayOfElements = [ { "username": "a", "attributes": { roles:["Tenant-Hyd"], groups:["InspectorIP", "InspectorFT"] } }, { ...

Is it possible to populate the blank cells in the weekday columns for previous and following months in a mat-datepicker or mat-calendar's display?

In order to enhance user experience, I am designing a calendar that allows users to select dates. My goal is to populate the empty cells at the beginning of the first week with dates from the previous and next months. For this project, I am utilizing the ...

Error: Failed to convert value "NaN" to ObjectId for the "_id" field

[ Issue resolved... the solution turned out to be surprisingly simple... $scope.article = articleFactory.getArticles().get({id:parseInt($stateParams.id,10)}) .$promise.then( should have been: $scope.article = articleFactory.getArticles().get ...

Guide on setting up an Express application to control LED light strips with a Raspberry Pi3

After setting up a node server on my Raspberry Pi to control an Adafruit Dotstar light strip, I encountered a problem. The sequence of colors on the light strip is triggered by an HTTP request to localhost:8000/fade, causing the server to run fade.js endle ...

Yeoman - Storing global settings efficiently

I have recently developed a Yeoman generator and am now looking to incorporate prompts for certain global configurations. My goal is to have the generator prompt users for their GitHub username and token during the initial run, and then somehow store this ...

Wrap each object in a container and then insert its key and values into that container using jQuery

How can I wrap each item and then insert the object's indexes and values into each created wrapper? I've attempted to accomplish this using the following code: $.ajax({ url: "some url", type: "GET", success: function(data) { var data ...

Analyzing the current time against a user-inputted time using Javascript

Looking at this html and javascript code, the goal is to compare an input time with the current time. If the input time is less than 2 hours, "Less time" should be displayed in the label; if it's more than 2 hours, then "sufficient time" should appear ...

various locations within a hexagonal zone or figure

In my project, I am working with a simple hexagonal grid. My goal is to select a group of hexagons and fill them with random points. Here is the step-by-step process of generating these points: I start by selecting hexagons using a list of hex coordinat ...

From AJAX response to React state attribute, store the JSON data

I have a component where I need to fetch freight values via ajax and store them in the state property of this class. import React, { Component } from 'react'; import Freight from './Freight'; import CreateFreightEntryModal from '. ...

Learn how to utilize Javascript to easily drag and drop an image within the same block

I am encountering an issue with dragging and dropping images or swapping them using JavaScript. I have tried to implement this in the code below, where clicking on icons moves them onto a colored div. However, I am now trying to drag and drop the images wi ...

Performing simultaneous AJAX requests in Javascript and jQuery

function makeCall(file, handlerFile, sendMethod, formData) { //console.log(instance.files); $.ajax({ url: handlerFile, type: sendMethod, xhr: function() { // Custom XMLHttpRequest var xhr = $.ajaxSettings.xhr() ...

A method for arranging an array of nested objects based on the objects' names

Recently, I received a complex object from an API: let curr = { "base_currency_code": "EUR", "base_currency_name": "Euro", "amount": "10.0000", "updated_date": "2024 ...

Guide to displaying a pop-up modal containing text and an image when clicking on a thumbnail image

Recently delving into Bootstrap 3, I created a thumbnail grid showcasing images related to various projects. My goal is to have a modal window pop up when clicking on an image. Within the modal, I want to display the selected image alongside some descrip ...

Cannot adjust Span content with JQuery

I am currently utilizing Bootstrap and JQuery for my project. HTML <div> <ul> <li><strong> Status : </strong><span id="monitorStatusSpan">1111</span></li> </ul> </div&g ...

Display elements exclusively when the class XY is in an active state using JavaScript

Hello everyone, I'm new to this platform and excited to share my first post. Currently, I find myself facing a major challenge as I navigate through a bootcamp program. I have been working on a website with different sections that require specific fu ...

Guide to setting up a trigger/alert to activate every 5 minutes using Angular

limitExceed(params: any) { params.forEach((data: any) => { if (data.humidity === 100) { this.createNotification('warning', data.sensor, false); } else if (data.humidity >= 67 && data.humidity <= 99.99) { ...

Is it possible to utilize a keyboard listener to activate a tooltip upon being invoked?

I've created a basic pie chart that shows a tooltip when you click on a pie wedge. Now, I want to achieve the SAME functionality, but for div elements located OUTSIDE of the pie chart. Situation: A user focusing on the 'Cat 1' div and ...

Are there equivalent npm variables like (`npm_config_`) available in yarn console scripts?

Utilizing variables in custom npm commands is possible (example taken from ): { "scripts": { "demo": "echo \"Hello $npm_config_first $npm_config_last\"" } } Can this functionality also be achieved ...