phpajaxyii2corsbasic-authentication

YII 2 REST CORS issue on remote server


I have developed a Yii2 REST API application. Everything is working fine in local. I have deployed the application to remote server. I could get api responses via Postman. But when i try to make a request with AJAX or Angular I get "Response for preflight has invalid HTTP status code 401" error. my Controller behaviors() method:

public function behaviors() {

    return array_merge(parent::behaviors(), [


        $behaviors['corsFilter']  = [
            'class' => \yii\filters\Cors::className(),
            'cors'  => [
                // restrict access to domains:
                'Origin'                           => ['*'],
                'Access-Control-Request-Method'    => ['GET','POST','PUT','DELETE','OPTIONS'],
                'Access-Control-Request-Headers' => ['*'],
                'Access-Control-Allow-Credentials' => true,
                'Access-Control-Max-Age'           => 3600,                 // Cache (seconds)
            ],
        ],
        $behaviors['authenticator'] = [
            'class' => AvnrHttpBasicAuth::className(),
        ],

    ]);
}

Response and Request Headers:

enter image description here

enter image description here

enter image description here

I assume this is CORS issue but i cannot figure out why this is not working on the remote server running on Centos with apache.

I have extended HttpBasicAuth and using my own AvnrHttpBasicAuth class

class AvnrHttpBasicAuth extends HttpBasicAuth
{
    public function authenticate($user, $request, $response)
    {

        $authHeader = $request->getHeaders()->get('Authorization');

        if ($authHeader !== null && preg_match("/^Basic\\s+(.*?)$/", $authHeader, $matches)) {

            $identity = $user->loginByAccessToken($matches[1], get_class($this));

            if ($identity === null) {
                $this->handleFailure($response);
            }
            return $identity;
        }
        return null;
    }
}

Solution

  • I have solved this issue with a minor modification to my .htaccess file. Thanks to this post

    these two lines below in .htaccess file did the trick.

    RewriteCond %{REQUEST_METHOD} OPTIONS
    RewriteRule ^(.*)$ $1 [R=200,L]
    Header always set Access-Control-Allow-Origin "*"