简体   繁体   中英

Yii2 REST API Basic Auth (SESSION OVERRIDE)

I have implemented findIdentityByAccessToken in my Users model.

public static function findIdentityByAccessToken($token, $type = null)
{
    $apiUser = ApiAccess::find()
        ->where(['access_token' => $token])
        ->one();
    return self::findOne(['id' => $apiUser->idUser]);
}

In the browser, if i'm logged into the system, I can hit an api get endpoint, enter my auth token and be authenticated properly.

However, If i am not logged in, I get kicked back to my login screen. Using a rest client, I am returned the HTML of the login screen.

This indicates 1 of 2 things in my eyes. Either, in the current state, it is requiring a 'logged in session' in order to access that api module. Or #2, I'm not properly passing the auth token.

My Request header:

 Accept: */*
 Cache-Control: no-cache
 Authentication: Basic base64('mytoken':)

How do I override my "default" login behavior? OR Properly send the authentication token?

You can override login method and loginByAccessToken from model User to change the login behavior . See: http://www.yiiframework.com/doc-2.0/yii-web-user.html

On the other hand, what you probably need (in case that you don't have it yet) is to write a controller and implement a login action . Then implement a class extending from AuthMethod and authenticate method (and maybe challenge method). After that you can add that class as a behavior to all your controllers (or even better make all your controller inherit from one controller with that behavior).

Plase take a look at this link: http://www.yiiframework.com/doc-2.0/guide-rest-authentication.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM