Wouter den Ouden
Wouter den Ouden

Reputation: 1523

Yii2 basic REST API authentication error

For some reason my Yii2 REST API authentication doesnn't work anymore.

I've written a function to get response from my API:

function getJSON($template_url) {
    $authorization = "Authorization: Bearer " . get_option("auth_key");

    // Create curl resource
    $ch = curl_init();
    // Set URL
    curl_setopt($ch, CURLOPT_URL, $template_url);
    // Return transfer as a string
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    // Set headers
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json', $authorization));
    // $output contains output as a string
    $output = curl_exec($ch);
    // Close curl resource
    curl_close($ch);

    return json_decode($output, true);
}

This gives me the following response:

Array ( [name] => Unauthorized [message] => You are requesting with an invalid credential. [code] => 0 [status] => 401 [type] => yii\web\UnauthorizedHttpException )

I've got this in my controller:

public function behaviors(){
    return [
        'contentNegotiator' => [
            'class' => ContentNegotiator::className(),
            'formats' => [
                'application/json' => Response::FORMAT_JSON,
            ],
        ],

        'authenticator' => [
            'class' => CompositeAuth::className(),
            'except' => ['activate'],
            'authMethods' => [
                HttpBearerAuth::className(),
            ],
        ]

    ];
}

And this is the findIdentityByAccessToken in the User class:

public static function findIdentityByAccessToken($token, $type = null) {
    $query = (new Query())
        ->select([
          'kl.access_token                                            access_token',
        ])
        ->from('klanten kl')
        ->where(['kl.access_token' => $token])
        ->one();
    return $query;
}

The database table has a column access_token. I've checked if the access token I use in the getJSON function is available in the database and it is. So I don't know what I'm doing wrong.

Upvotes: 1

Views: 2199

Answers (1)

nadar
nadar

Reputation: 1078

This can also be a Problem with the Request Headers on different Apache systems. Sometimes the Authorization Header gets lost. Add the below code to your htaccess:

 SetEnvIf Authorization .+ HTTP_AUTHORIZATION=$0

Missing Authorization Header discussion on GitHub

Upvotes: 0

Related Questions