Vinicius Aquino
Vinicius Aquino

Reputation: 737

What authentication should I use in an api developed with Yii 2?

I am having a question regarding REST API authentication in the Yii Framework. At the login endpoint, the user must enter the email and password, if he matches the data on the server, returns an access token, and will that token be used for the other endpoints? Is this or did I misunderstand?

If so, should login authentication be different from other endpoints? What authentication should I use in each of these situations?

HttpBasicAuth

HttpBearerAuth

QueryParamAuth

Another question I have is about the register endpoint, should it not have any authentication? How could I protect this url to prevent a user from making multiple records fakes?

Upvotes: 0

Views: 412

Answers (1)

Riyas Kp
Riyas Kp

Reputation: 151

Make sure your controllers are extended from yii\rest\Controller or yii\rest\ActiveController.

For login and registration, you should submit a POST request and validate the user input. To avoid multiple fake records ,you can varify the email or phone number should be unique and by sending a confirmation link or code.

For other controllers which need authentication you can either use HttpBearerAuth::className() or QueryParamAuth::className()

In case of HttpBearerAuth::className() we have to pass the access token in Authorization header, like Authorization: Bearer <access token here>

In case of QueryParamAuth::className() we have to pass the access token in the request url as a parameter, like api-url?access-token=.

You can add the authentication method to your controller like this

use yii\filters\auth\HttpBearerAuth;

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

Upvotes: 1

Related Questions