Michael St Clair
Michael St Clair

Reputation: 6605

Yii2 Rest API basic auth invalid credential

I'm using postman to test my API but for some reason it no longer works as every request is saying

You are requesting with an invalid credential.

I have noticed that if I look in the debugger that the Authorization request header does not show up. I have tested adding other headers in postman and those do show up.

I have the user model setup to find by access token in common\models\User:

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

And I have this in my behaviors function of the controller:

public function behaviors()
    {
        $behaviors = parent::behaviors();
        $behaviors['authenticator'] = [
            'class' => HttpBasicAuth::className(),
        ];
        $behaviors['access'] = [
            'class' => AccessControl::className(),
            'rules' => [
                [
                    'allow' => true,
                    'roles' => ['@'],
                    'verbs' => ['GET'],
                ],
            ],
        ];
        return $behaviors;
    }

Here is the components section of my main.php file:

'components' => [
        'user' => [
            'identityClass' => 'common\models\User',
            'enableAutoLogin' => false,
        ],
        'log' => [
            'targets' => [
                [
                    'class' => 'yii\log\DbTarget',
                    'levels' => ['error', 'warning'],
                ],
            ],
        ],
        'urlManager' => [
            'enablePrettyUrl' => true,
            'enableStrictParsing' => true,
            'showScriptName' => false,
            'rules' => [
                'v1/login' => 'v1/login',
                ['class' => 'yii\rest\UrlRule', 'controller' => ['v1/user']],
                ['class' => 'yii\rest\UrlRule', 'controller' => ['v1/userinfo']],
                'v1/<controller>/<action>' => 'v1/<controller>/<action>',
            ],
        ],
        'request' => [
            'parsers' => [
                'application/json' => 'yii\web\JsonParser',
            ]
        ]
    ],

Upvotes: 2

Views: 4850

Answers (3)

sj59
sj59

Reputation: 2162

In your .htaccess file add :

RewriteCond %{HTTP:Authorization} .
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

Upvotes: 2

Michael St Clair
Michael St Clair

Reputation: 6605

I had to add CGIPassAuth on to my directory configuration as Apache was hiding the authorization header.

Upvotes: 1

puneet gupta
puneet gupta

Reputation: 383

You need to pass Authorization Header with Basic format in your api. Ex- Basic {token}

Upvotes: 0

Related Questions