AngularJS implemented a header authorization feature

I've been attempting to include an authorization header in my requests, but I'm facing some issues.

Here is the code I am using:

var config = {headers: {
  'Authorization': token
  }
};
return $http.get('http://localhost:3000/apis/users/all', config);

I also tried this approach:

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

However, in both cases, the headers that are sent to the back-end contain additional information like:

Accept:*/*
Accept-Encoding:gzip, deflate, sdch
Accept-Language:es-ES,es;q=0.8,ca;q=0.6,en;q=0.4,gl;q=0.2
Access-Control-Request-Headers:accept, authorization
Access-Control-Request-Method:GET
Connection:keep-alive
Host:localhost:3000
Origin:http://localhost:8000
Referer:http://localhost:8000/
User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.85 Safari/537.36

What I actually need is a header that looks like this:

Authorization: token

Instead, I end up with:

Access-Control-Request-Headers:accept, authorization

As a result, the token value is not being included anywhere.

For my back-end, I am using expressjs and implementing CORS like so:

app.use(function(req, res, next) {
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, Authorization');
    next();
  });

Interestingly, when testing with the chrome extension Advance Rest Client, everything works fine. The request header does include "Authorization: valueOfToken".

Thank you for your assistance.

Answer №1

Security measures must be robust.

Clarify whether it is a Simple or Token Security Authorization

Example:

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

or

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

Answer №2

After encountering a similar issue, I discovered that the root cause was related to the Apache configuration on our server. One key insight I found that may help you is that my Authorization token is actually included in the preflight request headers rather than the main request headers. This means that it might not be immediately visible when inspecting the request headers using developer tools.

To address this issue, I made adjustments to my defaults as shown below:

app.config(function($httpProvider) {
    $httpProvider.defaults.common['Authorization'] = token;
    // For angular 1.5, use:  
    // $httpProvider.defaults.headers.common['Authorization'] = token;        
});

Answer №3

Here is a suggestion for you to try:

$http({

url : "127.0.0.1/login",
method : 'GET',
headers : {
      Content-Type : 'application/json',    
      Authorization: token
      }
}).success(function(data){
    alert("Logged in successfully");
}).error(function(error){
    alert("Error occurred during login");
})

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

Expressjs - Error: Headers already sent to the client and cannot be set

After testing various solutions from others, I am still unable to resolve this error. My objective is to iterate through each item in the array sourced below: novel.ts export let indexList = (req: Request, res: Response) => { novel.getAllDocuments ...

Enhance the functionality of jqGrid by customizing key bindings for arrow and tab keys

In order to enhance my jqGrid functionality, I am seeking to implement the ability for users to press different keys for specific actions. For example, pressing Enter should save data (which is currently working fine), while pressing the left arrow key sho ...

Enhancing jqgrid by incorporating cellattr to JSON colmodel

I've been experimenting with adding a custom cellattr function to my colmodel JSON response, but I'm having trouble getting it to work. I've tried applying classes and styles without success, so now I'm attempting to debug by logging so ...

Encountering a Null Pointer Exception when trying to locate an element on an AngularJS website using Selenium

Testing an AngularJS website with Selenium can be challenging due to angular directives, as mentioned in a blog. Despite encountering some stability issues such as failures and exceptions like "unable to locate Element," "No such element," or "Null pointer ...

The `Route` component is expecting a `function` for the `component` prop, but instead it received an `object`

For a while now, I've been grappling with an issue that seems to be unique to me. The problem lies within my component and container setup for the start screen rendering at the initial route. components/DifficultySelection.jsx import React from &apo ...

How can you use Knex to order the results for each WHERE clause in a SELECT query?

When querying a database using knex, the desired results should be ordered in a specific manner. The current code provides the required results but lacks the expected order. knex("FRUITTBL") .select("FruitTag", "FruitName", ...

Is there a way to determine if a certain class link within a DIV has been clicked and then replace the DIV's click functionality?

I have multiple DIV elements like the one below on my webpage: <div class='entry'> This is a statement <a title="Search @travel" class="app-context-link" href="">@travel</a> </div> When a DIV with the class .ent ...

What could be the reason for the inability of my external jQuery file to be implemented on a className within React

I am currently in the process of building a navigation menu for the mobile version of my website using jQuery. However, I'm encountering an issue when trying to integrate it within the className of my reactjs application. Despite placing the jQuery fi ...

Can you explain the contrast between ng-init and the initialization of a controller?

There are multiple techniques to initialize a variable in Angular. One method is by using the ng-init directive: <html> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"> </script> <body& ...

Tips for incorporating dynamic parameters/variables into templates displayed using ng-bind-html or a custom directive (within ng-repeat)

EDIT: I have created a solution sample based on the initial answer. However, I am open to further suggestions and would appreciate any help in filling the gaps in my knowledge (please refer to the comments). plnkr.co/edit/mqGCaBHptlbafR0Ue17j?p=preview OR ...

What's the best approach: Injecting a dependency into the main module or a controller in AngularJS?

I'm feeling a bit lost. There seems to be a difference in how dependencies are injected in AngularJS. Take for example the main module: angular.module("app", ["ui.router", "ui.bootstrap", "toaster"]); On the other hand, some dependencies can be inje ...

What is the best way to remove a specific HTML section using a JavaScript function?

I am struggling to figure out how to remove a specific HTML section using a button that is contained within the section itself. The section I want to delete was initially added by clicking a different button. Although I can successfully add a new section ...

Abort S3 file upload using ASW-SDK

Is there a way to abort an upload without raising an error Upload aborted. when calling upload.abort()? import { PutObjectCommandInput, S3Client } from '@aws-sdk/client-s3'; import { Progress, Upload } from "@aws-sdk/lib-storage"; cons ...

Exploring the possibilities of using the typeof operator within an Event

I want to log some information if the input value is a number. However, I am facing an issue where it's not working and no bugs are appearing. Here is a snippet of code from CodePen (https://codepen.io/matoung/pen/KBNmPP) let button = document.que ...

Using Javascript to dynamically add an element to an array with a unique index

Given let inputArray = []; $('some_selector').each(function() { let outer, inner; outer=$(this).parent().attr('some_property'); inner=$(this).attr('a_property'); if (!inputArray[outer]) inputArray[outer] = ...

What is the best way to implement data validation for various input fields using JavaScript with a single function?

Users can input 5 numbers into a form, each with the same ID but a different name. I want to validate each input and change the background color based on the number entered - red for 0-5, green for 6-10. I wrote code to change the color for one input box, ...

The HTML div captured with html2canvas is incomplete

I am currently developing a meme editor website utilizing the html2canvas library available at Below is the HTML code for the div I aim to capture: <div class="container"> <div id="theUserMeme"> <div class=& ...

Showcasing PHP variables within HTML using jQuery

I am currently looking for the best way to showcase information stored in a PHP variable, retrieved from a MySQL database. My initial thought was to use jQuery. Here are my questions: When a user inputs a number into a field, I receive that Member' ...

Exploring OOP Strategies within the Angular MVC Framework!

After coming across a question on Stack Overflow that was similar to mine, I realized I have a lot to learn about Object-Oriented Programming (OOP). Up until now, my coding experience has been mainly procedural. Before diving into my question, let me provi ...

"Guide to triggering the display of a particular div based on its class when clicked

I have multiple div elements with the class name dis HTML: <div class="dis">Content</div> <div class="dis">Content</div> <div class="dis">Content</div> and so on ... Additionally, there are various images: <img sr ...