Yii 2 RESTful API authenticate with OAuth2 (Yii 2 advanced template)

REST API is working without authentication methods. Now i wanted to authenticate REST API with OAuth2 authentication for API requests via mobile application. I tried with yii2 guide, but it didn’t work for me.

basically mobile user need to be login with username & password, if a username and password are correct, user need to be login and further API request need to be validate with token.

Do i need to create custom OAuth 2 client like this ?

Creating your own auth clients

access_token field in user table is empty. do i need to save it manually ?

how to return access_token as a respond?

is there any reason for user all three methods(HttpBasicAuth, HttpBearerAuth, QueryParamAuth) at once, why? how?

my application folder structure looks like below.




    api

    -config

    -modules

    --v1

    ---controllers

    ---models

    -runtime

    -tests

    -web

    

    backend

    common

    console

    environments

    frontend



api\modules\v1\Module.php




    namespace api\modules\v1;

    class Module extends \yii\base\Module

    {

        public $controllerNamespace = 'api\modules\v1\controllers';

    

        public function init()

        {

            parent::init(); 

            \Yii::$app->user->enableSession = false;       

        }  	

    }



api\modules\v1\controllers\CountryController.php




    namespace api\modules\v1\controllers;

    use Yii;

    use yii\rest\ActiveController;

    use common\models\LoginForm;

    use common\models\User;

    use yii\filters\auth\CompositeAuth;

    use yii\filters\auth\HttpBasicAuth;

    use yii\filters\auth\HttpBearerAuth;

    use yii\filters\auth\QueryParamAuth;

    

    /**

     * Country Controller API

     *

     * @author Budi Irawan <deerawan@gmail.com>

     */

    class CountryController extends ActiveController

    {

    	public $modelClass = 'api\modules\v1\models\Country';    

    

    	public function behaviors()

    	{

    	    $behaviors = parent::behaviors();

    	    $behaviors['authenticator'] = [

    	    	//'class' => HttpBasicAuth::className(),

    	        'class' => CompositeAuth::className(),

    	        'authMethods' => [

    	            HttpBasicAuth::className(),

    	            HttpBearerAuth::className(),

    	            QueryParamAuth::className(),

    	        ],

    	    ];

    	    return $behaviors;

    	}


    }




common\models\User.php




    namespace common\models;

    

    use Yii;

    use yii\base\NotSupportedException;

    use yii\behaviors\TimestampBehavior;

    use yii\db\ActiveRecord;

    use yii\web\IdentityInterface;

    

    class User extends ActiveRecord implements IdentityInterface

    {

        const STATUS_DELETED = 0;

        const STATUS_ACTIVE = 10;

        /**

         * @inheritdoc

         */

        public static function tableName()

        {

            return '{{%user}}';

        }

    

        /**

         * @inheritdoc

         */

        public function behaviors()

        {

            return [

                TimestampBehavior::className(),

            ];

        }

    

        /**

         * @inheritdoc

         */

        public function rules()

        {

            return [

                ['status', 'default', 'value' => self::STATUS_ACTIVE],

                ['status', 'in', 'range' => [self::STATUS_ACTIVE, self::STATUS_DELETED]],

            ];

        }

    

        /**

         * @inheritdoc

         */

        public static function findIdentity($id)

        {

            return static::findOne(['id' => $id, 'status' => self::STATUS_ACTIVE]);

        }

    

        /**

         * @inheritdoc

         */

        public static function findIdentityByAccessToken($token, $type = null)

        {

            

            return static::findOne(['access_token' => $token]);

        }


        

    }



user table




    id

    username

    auth_key

    password_hash

    password_reset_token

    email

    status

    created_at

    access_token

  

access_token was added after migrate user table

Check the yii2-oauth2-server module, it is working nicely for me.

You might be confusing two different things here. If you just want a token to authenticate a user, do not use OAuth2, which is designed to allow a 3rd-party to authenticate your users. It sounds like you just want to return a code to the user when they login and then use one of the auth classes to login. You will need to generate and save the access token yourself.

Note that you should use https for this process since HTTP basic and query string auth don’t support any security of the credentials.

You can use OAuth2 if you really want. I did something with Google so that when access token is passed in, it calls Google to verify the token.

1 Like

you can use this sample if you want.

this is a Yii2 Advanced template used to build a RESTful API with Oath2.0 authentication but i have not used Yii2’s native Rest or any other modules for it as its going to be very difficult for me to implement custom features in future.

DEMO:

http://yii2-rest.cloudboxes.org/

Login: admin/admin123