Yii2 Rest API Bearer Authentication

2019-04-07 12:22发布

I've made a Yii2 REST API. With the API you can get a list of cars. Now I want to use the Bearer Authentication to protect the API. But I don't know how it works.

First of all. I set up the authenticator in the behaviors method of my controller.

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

This works just fine. If I go to the URL I will get an 'Unauthorized' message.

In my wordpress plugin I've made an function to use the API and set the header with the authentication key.

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

But now my question is. How can I check in the API if this key is valid and give me the response. I want to search for the key in de database and if it exists it should also give me the id or email thats in the same row.

I have no idea how to do this.

1条回答
beautiful°
2楼-- · 2019-04-07 13:17

\yii\filters\auth\HttpBearerAuth::authenticate() will simply call \yii\web\User::loginByAccessToken() :

$class = $this->identityClass;
$identity = $class::findIdentityByAccessToken($token, $type);

So you just need to implement findIdentityByAccessToken() in your user identity class, e.g. :

public static function findIdentityByAccessToken($token, $type = null)
{
    return static::findOne(['auth_key' => $token]);
}
查看更多
登录 后发表回答