Yii2 Rest API Bearer Authentication

10,108

\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]);
}
Share:
10,108

Related videos on Youtube

Wouter den Ouden
Author by

Wouter den Ouden

Updated on June 04, 2022

Comments

  • Wouter den Ouden
    Wouter den Ouden almost 2 years

    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.

  • Salem Ouerdani
    Salem Ouerdani about 8 years
    @WouterdenOuden when findIdentityByAccessToken returns null authentication will be rejected. so do whatever logic you need inside it (like also checking token validity) and return null if authentication should fail or return a user instance that Yii::$app->user->identity will hold so you can use it any where inside your app. check this and this for more details.
  • Salem Ouerdani
    Salem Ouerdani about 8 years
    ...you may also need to build Actions to handle login, signup, ... like in this example.
  • Wouter den Ouden
    Wouter den Ouden about 8 years
    So I could just make a query with one() and if it doesn't find anyting it will return null? and if it finds data the authentication would be successful?
  • Salem Ouerdani
    Salem Ouerdani about 8 years
    exactly. just remember that findIdentityByAccessToken should return either null or a user instance. (note that by default findOne() will return null if user not found)
  • Wouter den Ouden
    Wouter den Ouden about 8 years
    Is there a way to test if my getJSON function sets the httpheader? because I can't get it to work.