M
M
Maxim Timofeev2016-11-02 15:30:18
Yii
Maxim Timofeev, 2016-11-02 15:30:18

What is wrong with Yii2 rest api authorization?

I decided to play around with REST, figured it out to a greater extent, but got stuck with authorization. It seems to understand the principle, but apparently not correctly.
Here is the controller:

<?php
namespace frontend\controllers;

use yii;
use yii\rest\Controller;
use yii\filters\auth\QueryParamAuth;

class QuestionController extends Controller
{

  public function behaviors()
  {
    $behaviors = parent::behaviors();
    $behaviors['authenticator']['class'] = QueryParamAuth::className();
    $behaviors['authenticator']['only'] = ['init'];
    return $behaviors;
  }

  public function actionInit(){
    return 124;
  }
}

Here is the method in the User model:
public static function findIdentityByAccessToken($token, $type = null)
    {
        return static::findOne(['auth_key' => $token]);
    }

Here is an ajax request to api on another site:
$(function() {
    $.ajax('https://mysite/api/init',{
        dataType: "json",
        method: 'post',
        data: {access_token:'1NLS4Os8zNwdeImN2hUUcaDpnTzNrfeM'},
        success: function (data) {
            $("#question").attr('data-key',data);
            $("#loader").hide();
            $("#test-body").show();
        }
    });
});

With routing everything is OK, the request gets to the address. Passes the existing auth_key, but the server responds like this:
code:0
message:"Your request was made with invalid credentials."
name:"Unauthorized"
status:401

It seems that the token was not transferred correctly, as if he does not see it. Already five times I went through all the methods and I don’t understand what’s wrong. Help needed.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alex Khizhniy, 2016-11-04
@mendler

data: {access_token:'1NLS4Os8zNwdeImN2hUUcaDpnTzNrfeM'}

The key is access-token, not access_token,
https://github.com/yiisoft/yii2/blob/master/framew... , line 21
If an access_token is required, then it must be overridden in the behavior settings.

S
Slavanb, 2017-12-29
@Slavanb

$behaviors['authenticator']['class'] = QueryParamAuth::className();
$behaviors['authenticator']['tokenParam'] = 'token'; //- default access-token
// change get parameter access-token to token
// https://mysite/api/init?token=FFFF70it7tzNsHddEiq0...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question