1

I am trying to implement authentication in rest API with Https Bearer Auth I don't have a table of registered users but a table with other apps that have "access_token" permission to access my API.

Is this correct and safe? Will "access_token" be the same forever? and put it directly in the code?

controller.php

public function behaviors()
    {
        $behaviors = parent::behaviors();
        $behaviors['authenticator'] = [
            'class' => CompositeAuth::className(),
            'authMethods' => [
                HttpBearerAuth::className(),

        ]];
        return $behaviors;
    }

application components

'components' => [
        'user' => [
            'identityClass' => 'common\models\ApiAccess',
            'enableSession' => false,
            'loginUrl' => null,
        ],
    ],

common/models/ApiAccess (instead common/models/User)

....
 public static function findIdentityByAccessToken($token, $type = null)
    {
        return static::findOne(['access_token' => $token]);
    }

and in this table i have fields: id, app_name, access_token.

client side

in client side i use yiisoft/yii2-httpclient and i have this code.

$client = new Client();
        $response = $client->createRequest()
            ->setMethod('GET')
            ->setUrl('http://etc/etc')
            ->addHeaders(['Authorization' => 'Bearer 56265883-****-****-****-************'])
            ->send();
        if ($response->isOk) {
            code.....
        }
Moutinho
  • 339
  • 8
  • 22
  • 1
    i think this link will help you: https://stackoverflow.com/questions/35720399/yii2-rest-api-bearer-authentication – Serghei Leonenco Aug 20 '19 at 03:59
  • 1
    you can bind the api-key and the domain names that are going to consume your api in case your api-key isnt going to change because if somehow anyone steals your clients API key you still have restriction applied with CORS to allow only those domains that are trust worthy – Muhammad Omer Aslam Aug 20 '19 at 04:35
  • @SergheiLeonenco basically this is the same as my code. – Moutinho Aug 20 '19 at 15:51
  • @MuhammadOmerAslam this was very useful thanks! – Moutinho Aug 20 '19 at 15:52

0 Answers0