D
D
Dilik Pulatov2017-10-22 17:21:29
Yii
Dilik Pulatov, 2017-10-22 17:21:29

How to implement REST authorization in Yii2?

Hello!
I have such a task...authorization and registration through the RESTful API in Yii2
I don't know how to implement this yet , tell me
where to start? For example, I created a user rest controller. and the form with which the Ajax request goes
in the rest controller everything works as it should, list output, additions and deletions .. but the problem is how to implement authorization? generation of a token, time of a token, etc.
and with an Ajax request, how can I send the received token to the header? and generally add a token in the header?
if it’s not difficult to explain in detail .. I read a lot of the article but did not understand)
an example of the codes that I wrote

<?php 
namespace app\controllers;

use Yii;
use yii\rest\ActiveController;
 
class UserController extends ActiveController{
  public $modelClass = 'app\models\Users';
  public function beforeAction($action){
  	if(parent::beforeAction($action)){
  		Yii::$app->response->headers->add("Access-Control-Allow-Origin","*");
  		return true;
  	}
  }

}

$.ajax({
      url: 'http://api.loc/users/login',
      method: "POST",
      data: {
        username:$("form#auth input#username").val(),
        password:$("form#auth input#password").val()
      },
      dataType: "json",
      success: function(res){
          console.log("USER: ", res.content);
      },
      error: function(err){
        console.log("ERROR: ", err.responseJSON);
        $.each(err.responseJSON, function(i, v){
          $('#errors').append("<p><b>"+v.field+":</b> "+v.message+"</p>");
        });
      },
    });

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry, 2017-10-23
@slo_nik

Goodnight.
Take a look here , it seems to be the answer to your question.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question