Yii2 Rest API user authentication

Nitin Pund picture Nitin Pund · Jan 5, 2017 · Viewed 8.4k times · Source

I am implementing Rest API in yii2. I want to authenticate the user using access token. I have referred various SO answers as follows

But I m not clear, which authentication method I should use and how I will get user identity.

I have created findIdentityByAccessToken() method in my user identity class as suggested in Yii2 Rest guide .

Below is the behaviour implemented in my controller

public function behaviors() {
        $behaviors = parent::behaviors();
        $behaviors['authenticator'] = [
            'class' => HttpBasicAuth::className(),
            'except' => ['login','forgot-password']
        ];

        return $behaviors;
    }

now, how I will get the user identity inside my controller action? As far as i know, access token will be set from the web service inside request header.

Note : I am using Yii2 advanced app please help me.

Answer

Tim picture Tim · Jan 5, 2017

Simple answer there's more than one possibility to implement this behavior.

Both HttpBearerAuth and HttpBasicAuth can use the findIdentityByAccessToken() methode when configured correctly. the behavior you should use depends on the way you want users to authenticate themselves.

if you read the documentation of HttpBasisAuth HttpBasicAuth you'll see

The default implementation of HttpBasicAuth uses the loginByAccessToken() method of the user application component and only passes the user name. This implementation is used for authenticating API clients.

loginByAccesToken will invoke the findIdentityByAccesToken methode You can manipulate this behavior by defining a closure in the auth attribute see auth attribute.

HttpBeareAuth almost does the same. it also implements the loginByAccessToken

So what make the two different from each other? simple the location where the get the data from. where HttpBasicAuth expects that client has set the basic header example header('Authorization: Basic '. base64_encode("user:password")); (PHP has build in support for this see: http://php.net/manual/en/features.http-auth.php)

the HttpBearerAuth expects that the header is defined as the following header('Authorization: Bearer '. $token);

So the solution you should use depends on the way you want users/clients to authenticate themselves. you could also use the QueryParamAuth which gives the users the possibility to authenticate themselves whit a GET param see queryparamauth

And if you want to use a custom header let's say X-API-Token create your own custom class that implements the AuthMethod interface see AuthMethod

Hope this helps