2

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.

georgeawg
  • 48,608
  • 13
  • 72
  • 95
Vinoth Kumar
  • 489
  • 3
  • 17
  • 45

3 Answers3

8

Add Authorization to the CORS Check:

$config['allowed_cors_headers'] = [
  'Authorization',
  'Origin',
  'X-Requested-With',
  'Content-Type',
  'Accept',
  'Access-Control-Request-Method'
];
georgeawg
  • 48,608
  • 13
  • 72
  • 95
2

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

Uday
  • 1,165
  • 9
  • 12
  • I have tried like this also, still same issue. this.headers.append('Access-Control-Allow-Headers', 'Authorization, Content-Type,Content- Range, Content - Disposition, Content - Description'); this.headers.append('Access-Control-Allow-Methods', 'GET, POST,OPTIONS'); this.headers.append('Access-Control-Allow-Origin', '*'); – Vinoth Kumar May 27 '17 at 05:58
  • Are you doing this in the right place? I mean you should do this on server config. Your code looks like you are doing it on the client request. – Uday May 27 '17 at 06:03
  • I have added in my rest controller header("Access-Control-Allow-Headers: Authorization, Content-Type, Content-Range, Content-Disposition, Content-Description"); header('Content-type: application/json'); header("Access-Control-Allow-Origin: *"); header("Access-Control-Allow-Methods: GET"); header("Access-Control-Allow-Methods: GET, OPTIONS"); – Vinoth Kumar May 27 '17 at 06:06
  • 1
    What do you see for the "Access-Control-Allow-Headers" in the preflight response? If it doesn't contain, "Authorization" certainly need to check the server config. – Uday May 27 '17 at 06:11
0

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);
}
}