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.

3
  • check in server configuration. header allowed or not. Commented May 27, 2017 at 5:58
  • add "Access-Control-Allow-origin" plugin into chrome for fix this issue but its not permanent solution. Commented May 27, 2017 at 6:01
  • Possible duplicate of How to create cross-domain request (Angular 2)? Commented May 27, 2017 at 7:43

3 Answers 3

8

Add Authorization to the CORS Check:

$config['allowed_cors_headers'] = [
  'Authorization',
  'Origin',
  'X-Requested-With',
  'Content-Type',
  'Accept',
  'Access-Control-Request-Method'
];
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much, It helped me. It is working well after i add Authorization in allowed_cors_headers
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

4 Comments

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', '*');
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.
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");
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.
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);
}
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.