Angular 2 Request header field Authorization is not allowed by Access-Control-Allow-Headers in preflight response

6.7k Views Asked by At

I'm using codeigniter REST API for my server application. And client as Angular2, in my REST API I have given basic auth. I have set like

$config['rest_auth'] = 'basic';

And

$config['rest_valid_logins'] = ['uname' => 'pwd'];

And also for CORS Check i have used below code,

$config['check_cors'] = TRUE;
$config['allowed_cors_headers'] = [
  'Origin',
  'X-Requested-With',
  'Content-Type',
  'Accept',
  'Access-Control-Request-Method'
];
$config['allowed_cors_methods'] = [
  'GET',
  'POST',
  'OPTIONS',
  'PUT',
  'PATCH',
  'DELETE'
];
$config['allow_any_cors_domain'] = TRUE;

And also I have tried explicitly tried with in my rest controller,

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Content-Range, Content-Disposition, Content-Description');

I used below code in angular,

import { Component, OnInit } from '@angular/core';
import { Http, Headers, RequestOptions  } from '@angular/http';
import { FormGroup, AbstractControl, FormBuilder, Validators } from '@angular/forms';
import { Router } from '@angular/router';
import { CommonService, BaseAPIURL } from '../common/common.service';
export class Login implements OnInit {
 private headers: Headers;
  constructor(fb: FormBuilder, private router: Router, private http: Http,
    private commonService: CommonService) {
     this.headers = new Headers();
     this.headers.append('Authorization', 'Basic ' + btoa('uname:pwd'));
     this.headers.append('Content-Type', 'application/json');

  }
 ngOnInit() {
  }

  public onSubmit(values: Object): void {
    this.submitted = true;
    if (this.form.valid) {
      let options = new RequestOptions({ headers: this.headers });
      this.http.post(this.getuserLoginURL, JSON.stringify(values),  options ).subscribe(
        response => {
          let result = response.json();
          this.errorMessage = result.message;
        },
        error => {
          this.isDisabled = false;console.log(error);
          if (error.status == 400) {
            this.errorMessage = JSON.parse(error._body).message;
          } else {
            this.errorMessage = 'Internal server error. please contact admin.';
          }
        }, () => {
        });
    }
  }
}

When i have check with postman it is working well without any issue. When check with angular error comes like,

XMLHttpRequest cannot load http://localhost:97/sencogold/index.php/Adminaccount_api/login_adminuser. Request header field Authorization is not allowed by Access-Control-Allow-Headers in preflight response.

If i false the rest auth and remove the Authorization header it is working well without check the api user name and password

$config['rest_auth'] = FALSE;

and in angular

 this.headers = new Headers();
    //this.headers.append('Authorization', 'Basic ' + btoa('lmxretail:lmx@2017'));
    this.headers.append('Content-Type', 'application/x-www-form-urlencoded');

Please help any one to apply authentication for my api.

3

There are 3 best solutions below

0
On

in php codeigniter backend just put this header in the construct() of your api controller. example:

class ApiController extends CI_Controller {
    function __construct(){
        
            parent::__construct();
            header('Access-Control-Allow-Origin: *');
            header("Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE");            
            header("Access-Control-Allow-Headers: Origin,X-Requested-With,Content-Type,Accept,Access-Control-Request-Method,Authorization,Cache-Control");
            header('Content-Type: application/json'); 
    }
public function index(){
        $MYARRAY = array(1);
        echo json_encode($MYARRAY);
}
}
1
On

Add Authorization to the CORS Check:

$config['allowed_cors_headers'] = [
  'Authorization',
  'Origin',
  'X-Requested-With',
  'Content-Type',
  'Accept',
  'Access-Control-Request-Method'
];
4
On

In order for your preflight request to succeed, the server controller must accept the "Authorization" header as valid. You can do that by adding the "authorization" key along with other allowed headers values:

Access-Control-Allow-Headers: Authorization, Content-Type, Content-Range, Content-Disposition, Content-Description