AngularJS Cross-Origin Resource Sharing request with a customized header

I'm currently facing issues with enabling CORS on my server while using AngularJS. I am working with Angular version 1.2.16 and below is my server configuration:

Header set Access-Control-Allow-Origin "*"
Header set Access-Control-Allow-Headers "Content-Type, X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Date, X-Api-Version, X-File-Name, Authorization"
Header set Access-Control-Allow-Methods "POST, GET, PUT, DELETE, OPTIONS"
Header set Access-Control-Allow-Credentials "true"

I am able to make the following request successfully:

$http.post(configuration.authUrl, {username: 'username', password: 'password'})
    .success(function (data) {
         $cookieStore.put(configuration.sessionName, {
             token: data.authenticationToken,
              user: data.user
         });
    })
    .error(function () {}));

This request does not involve any custom headers.

However, when I attempt to make the following request: Balance.get(), where Balance is:

angular.module('portalApp')
    .factory('Balance', ['$resource', 'Auth', 'configuration', function ($resource, Auth, configuration) {
        return $resource(configuration.balanceUrl, {}, {
            get: {
                method: 'GET',
                isArray: false,
                headers: {
                    Authorization: Auth.getAuthToken()
                }
            }
        });
    }]);

I receive a 401 Unauthorized response for the balanceUrl.

In the configuration, I have included:

$httpProvider.defaults.useXDomain = true;
delete $httpProvider.defaults.headers.common['X-Requested-With'];

I even tried adding

$http.defaults.headers.common.Authorization = Auth.getAuthToken();
before the $resource in the Balance resource factory but that did not resolve the issue.

The headers sent in the preflight OPTIONS request do not include the Authorization header, regardless of the method used. Below are the request headers for the preflight OPTIONS request.

OPTIONS /api/v1.0/user/orders HTTP/1.1
Host: host
Connection: keep-alive
Cache-Control: no-cache
Access-Control-Request-Method: GET
Pragma: no-cache
Origin: origin
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.153 Safari/537.36
Access-Control-Request-Headers: accept, authorization
Accept: */*
Referer: referer
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-US,en;q=0.8

Do you have any suggestions or solutions?

Answer №1

It is a well-known fact that combining Access-Control-Allow-Origin "*" with

Access-Control-Allow-Credentials "true"
is not allowed.

Answer №2

After thorough investigation, it was determined that the issue did not stem from AngularJS or Apache configuration, but rather from a backend server app (Java). The problem arose due to restrictions on URLs for all HTTP methods, which led to denial of access when an OPTIONS request was made by AngularJS, resulting in a 401 error.

The issue was resolved by implementing the following:

if(!authenticationService.isTokenValid(glueToken) && !((HttpServletRequest)servletRequest).getMethod().equals(HttpMethod.OPTIONS.toString()) ){
  response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
} else {
  filterChain.doFilter(servletRequest, servletResponse);
}

Instead of:

if(!authenticationService.isTokenValid(glueToken)){
  response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
} else {
  filterChain.doFilter(servletRequest, servletResponse);
}

Answer №3

What if we enable pre-flight request options without requiring authentication or authorization in an anonymous manner? Link to source

Answer №4

Although my strategy differs slightly, the core concept remains unchanged.

To start off, consider adding 'Bearer' in front of your access token:

headers: {
    Authorization: 'Bearer ' + Auth.getAuthToken()
}

If that doesn't work, make sure app.config is properly configured and defined as a variable:

app.config(
    function($httpProvider) {
        $httpProvider.defaults.headers.common = {};
        $httpProvider.defaults.headers.post = {};
        $httpProvider.defaults.headers.put = {};
        $httpProvider.defaults.headers.patch = {};

        $httpProvider.defaults.headers.common.Authorization = 'Bearer ' + Auth.getAuthToken();
    }
);

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

Exploring how to alter state in a child component using a function within the parent component in React

class ParentComponent extends Component { state = { isDialogOpen: false, setStyle: false } handleClose = () => { this.setState({ isDialogOpen: false, setStyle: false }) } handleOpen = () => { this.setState({ isDialogOpen: true ...

how to load CSS and JS files on certain views in Laravel 5.2

Currently, I am facing a situation where I need to ensure that the CSS and JS files are loaded only on specific views in Laravel 5.2. Due to my boss's decision to eliminate RequireJS for loading JS files on our blade templates, we are now exploring a ...

What is the simplest method for expanding an attribute directive in AngularJS?

I am looking to create a unique ng-if directive, but I am struggling to find good examples on how to accomplish this. My goal is: <div my-if="someText">....</div> I want this to translate to <div ng-if="true|false">....</div> ...

How to create a looping animation effect for a div using CSS on hover

Using Bootstrap framework with Wordpress site .test { position: absolute; z-index: 9; left: 50%; height: 10em; width: 10em; margin-left: -5em; background-size: cover; opacity: 0; transition: opacity 0.5s ease; transform: translateY(- ...

PHP enables users to look at manual values in columns and MySQL values row by row

I have created a PHP program to organize seating arrangements for an exam hall. The user manually inputs the names of the halls, which should be displayed in columns in a table. The register numbers are fetched from a MySQL database and should be displayed ...

Which RxJS operators necessitate unsubscription?

It can be confusing to know which operators in RxJS must be unsubscribed from to prevent subscription leaks. Some, like forkJoin, complete automatically, while others, such as combineLatest, never complete. Is there a comprehensive list or guideline availa ...

Should scripts be replayed and styles be refreshed after every route change in single page applications (SPA's)? (Vue / React / Angular)

In the process of creating a scripts and styles manager for a WordPress-based single page application, I initially believed that simply loading missing scripts on each route change would suffice. However, I now understand that certain scripts need to be ex ...

Dropdown Pattern with React CTA Modal

While using MaterialUI's ButtonGroup for a dropdown menu, I encountered an issue trying to set up a series of CTAs that are easily interchangeable within it. The goal is to have all components reusable and the choices in the dropdown dynamic. const C ...

Guide on how to smoothly navigate through an HTML page to a specific anchor point

Is there a way to use JavaScript to make the browser scroll the page to a specific anchor? In my HTML code, I have set either a name or id attribute like this: <a name="anchorName">..</a> or <h1 id="anchorName2">..&l ...

Update the button text dynamically when clicked without using an identifier or a class

If we take a look at my button in the following code: <input type="button" value="BLUE" name="button_blue" /> My goal is to have the value="BLUE" changed to value="RED" or any other desired value when the button is clicked. ...

The eternal dilemma: async with axios or simply axios, which will you choose?

Is there a difference between these two useEffect functions? useEffect(()=>{ async function fetchData(){ await axios .get(path, config) .then(resp=>console.log(resp)) .catch(error=>console.log(error)) } fetchData(); },[ ...

Tips for customizing fonts in react-pdf

I am having difficulty in changing fonts within react-pdf. // Register Font Font.register({ family: "Roboto", src: "https://cdnjs.cloudflare.com/ajax/libs/ink/3.1.10/fonts/Roboto/roboto-light-webfont.ttf" }); The default f ...

Having trouble implementing new controllers in AngularJS UI-Router for nested states?

I'm currently facing an issue with nested states in the ui-router. My task involves rendering a page that includes regions, countries, and individuals per country. In the index.html file, there are three regions represented as links: EMEA, APAC, and ...

The ".splice()" method continuously removes the final element from an array

I have implemented a function on my form that allows me to add multiple file inputs for various images by clicking a button. Although this functionality is working correctly, I am facing an issue while trying to delete an input field using .splice. Instead ...

Utilizing JavaScript to access carousel images and captions, then displaying them in a modal with a click option

I'm currently in the process of setting up a carousel feature that will display the image along with its corresponding caption in a modal window once the user clicks on the image. Although I have managed to successfully display the image in the modal ...

Animated dropdown feature spanning the entire width of the screen

I successfully developed a basic dropdown menu with full-width sub-menu functionality. Check it out on jsFiddle: $(document).ready(function(){ $(".drop").hide(); $(".link-1").mouseenter(function(){ $('.link-1-drop').slide ...

Using ui-tabs with Ng-repeat to create both dynamic and static tabs

I'm currently working on creating a date tabs feature where users can click to add more tabs. Below is a snippet of the code I'm using: `<uib-tabset justified="true" class="ui-tab"> <uib-tab ng-repeat="date in dates track by $index" hea ...

Acquiring the API through the callback function within a React application

I wrote a function that connects to an API and fetches data: import {API_KEY, API_URL} from "./constants"; export const getOperations = async (id, successCallback) => { try { const response = await fetch(`${API_URL}/tasks/${ ...

What is the best way to assign the "active" class to a navigation list item using JavaScript within Bootstrap 4?

Update: just to clarify, I'm working on activating the navbar button based on the current page. I have a navigation bar set up and I am trying to dynamically add an "active" class to the li element when you are on that specific page. However, for som ...

Are Twitter Bootstrap buttons compatible with iPad devices?

Have you ever tried using the attractive buttons provided by Twitter? They can be a great alternative to standard radio/checkbox options. If you have used them in your production, how effective were they? I am particularly curious about their compatibilit ...