Yii2 REST API BasicAuth не работает

Я реализую модуль аутентификации REST API следующим образом: 1. Создайте пользователя администратором 2. Первый раз: войдите в систему с помощью базовой аутентификации, чтобы вернуть access_token 3. Используйте access_token на шаге 2 для аутентификации пользователя. QueryParamAuth

поскольку эта инструкция работает с QueryParamAuth https://github.com/yiisoft/yii2/blob/master/docs/guide/rest-authentication.md

Но это не работает на шаге 2. Аутентификацию по BasicAuth я отлаживаю. $this->auth всегда возвращает ноль. Хотя $username и $password правы

class HttpBasicAuth extends AuthMethod
/**
 * @var callable a PHP callable that will authenticate the user with the HTTP basic auth information.
 * The callable receives a username and a password as its parameters. It should return an identity object
 * that matches the username and password. Null should be returned if there is no such identity.
 *
 * The following code is a typical implementation of this callable:
 *
 * ```php
 * function ($username, $password) {
 *     return \app\models\User::findOne([
 *         'username' => $username,
 *         'password' => $password,
 *     ]);
 * }
 * ```
 *
 * If this property is not set, the username information will be considered as an access token
 * while the password information will be ignored. The [[\yii\web\User::loginByAccessToken()]]
 * method will be called to authenticate and login the user.
 */
public $auth;
public function authenticate($user, $request, $response)
{
    $username = $request->getAuthUser();
    $password = $request->getAuthPassword();
    if ($this->auth) {
        if ($username !== null || $password !== null) {
            $identity = call_user_func($this->auth, $username, $password);
            var_dump($identity);
            die();
            if ($identity !== null) {
                $user->switchIdentity($identity);
            } else {
                $this->handleFailure($response);
            }
            return $identity;
        }
    } elseif ($username !== null) {
        $identity = $user->loginByAccessToken($username, get_class($this));
        if ($identity === null) {
            $this->handleFailure($response);
        }
        return $identity;
    }

    return null;
}

Мой вопрос: как я могу реализовать функцию $this->auth?


person huythang    schedule 22.12.2014    source источник


Ответы (2)


Базовая HTTP-аутентификация

// код контроллера

Способ 1: аутентификация пользователя с использованием токена аутентификации

use yii\filters\auth\HttpBasicAuth;

public function behaviors()
{
    $behaviors = parent::behaviors();
    $behaviors['authenticator'] = [
        'class' => HttpBasicAuth::className(),
    ];
    return $behaviors;
}

Приведенный выше код будет проверять пользователя по токену доступа (как указано в документе)

когда окно предлагает ввести имя пользователя и пароль

имя пользователя: hErEaccE55T0ken

пароль:

Способ 2. Чтобы реализовать пользовательскую аутентификацию с использованием имени пользователя и пароля, пример кода (работает код Криса)

я использую user_email, user_password

public $user_password;


public function behaviors()
{
    $behaviors = parent::behaviors();
    $behaviors['authenticator'] = [
        'class' => HttpBasicAuth::className(),
        'auth' => [$this, 'auth']
    ];
    return $behaviors;
}

/**
 * Finds user by user_email and user_password
 *
 * @param string $username
 * @param string $password
 * @return static|null
 */
public function Auth($username, $password) {
    // username, password are mandatory fields
    if(empty($username) || empty($password))
        return null;

    // get user using requested email
    $user = \app\models\User::findOne([
        'user_email' => $username,
    ]);

    // if no record matching the requested user
    if(empty($user))
        return null;

    // hashed password from user record
    $this->user_password = $user->user_password;

    // validate password
    $isPass = \app\models\User::validatePassword($password);

    // if password validation fails
    if(!$isPass)
        return null;

    // if user validates (both user_email, user_password are valid)
    return $user;
}
person abdulwadood    schedule 30.04.2015

Я реализую HttpBasicAuth->auth в своем контроллере, где я прикрепляю HttpBasicAuth к такому поведению:

class MyController extends Controller
{
    public function behaviors()
    {
        $behaviors = parent::behaviors();

        $behaviors['authenticator'] = [
            'class' => HttpBasicAuth::className(),
            'auth' => [$this, 'auth']
        ]

        return $behaviors;
    }

    public function auth($username, $password)
    {
        // Do whatever authentication on the username and password you want.
        // Create and return identity or return null on failure
    }

    // ... Action code ...
}
person chrislondon    schedule 29.01.2015