Yii2 REST API 认证 [英] Yii2 REST API authentication

查看:55
本文介绍了Yii2 REST API 认证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找教程并阅读 yii 关于 REST API 和身份验证的官方教程,但我无法弄清楚如何通过 REST API 对用户进行身份验证.如何配置它.我正在使用 Yii 2.0.1 高级模板.我一直在尝试这样做,但我不确定我是否做得对,以及验证用户身份的正确方法是什么.

I was looking for tutorials and read yii's official tutorial about REST API and authentication, but I just can't figure it out how to authenticate user via REST API. How to configure it. I'm using Yii 2.0.1 advanced template. I've been trying to do it, but I'm not sure if I'm doing it right and what's the right way of authenticating user.

下面是我的代码,它返回正确的数据.但我不确定这是否是正确的方法.因为在另一个控制器中,我需要检查用户是否登录以访问操作.

Below is my code and it returns correct data. But I'm not sure if it is the right way. Because In another controller I need to check if user is logged in to access actions.

<?php
namespace api\modules\backend\controllers;

use yii\rest\ActiveController;
use yii\filters\auth\CompositeAuth;
use yii\filters\auth\HttpBasicAuth;
use yii\filters\auth\HttpBearerAuth;
use yii\filters\auth\QueryParamAuth;

use Yii;
use dektrium\user\models\LoginForm;
use dektrium\user\models\User;

class UserController extends ActiveController
{
    public $modelClass = "dektrium\user\models\User";

    public function actionLogin()
    {
        $model = new LoginForm;

        if ($model->load(\Yii::$app->getRequest()->post()) && $model->login()) {
            //return $this->goBack();
             echo \Yii::$app->user->identity->getAuthKey();
            //echo json_encode(['a'=>Yii::$app->user->getId()]);
        }

    }

  public function actionIndexx()
    {
        if (\Yii::$app->user->isGuest) {
            throw new \HttpHeaderException();
        }
        echo \Yii::$app->user->getId();
    }

}
?>

推荐答案

我认为登录过程大致相同.当您使用 REST API 时,只有 Url 结构不同,但是您在操作中做什么取决于您.您可以在应用程序中的任何位置使用此代码检查用户是否已登录:

I think login process will be more or less same. Only Url structure is different when you use REST API, but what you do in actions is up to you. Any where in you application you can check if user is logged in or not with this code:

\Yii::$app->user->isGuest

如果用户未登录则返回真,否则返回假.

It will return true if user is NOT logged in otherwise false.

如果您需要限制对操作的访问,那么您可以使用 访问控制过滤器基于角色的访问控制

And if you need to restrict access to actions then you can use Access Control Filter or Role Based Access Control

我再次认为 Access Control Filter 实现应该是相同的,即使对于 REST API.

Again I think Access Control Filter implementation should be same even for REST API.

这篇关于Yii2 REST API 认证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆