dongwende1984 2015-03-17 05:20
浏览 64
已采纳

如何在Yii2中实现自己的身份验证?

I'm trying to follow the authentication tutorial* for Yii2 but due to the project's requirements I need to build custom authentication. Although the tutorial does state you can make your own it doesn't elaborate on how. What files do I need to create and where and what values do I need to add to $behaviors['authenticator'] to refer to my custom auth module?

*https://github.com/yiisoft/yii2/blob/master/docs/guide/rest-authentication.md

  • 写回答

1条回答 默认 最新

  • douji9184 2015-03-17 05:38
    关注

    The question is too broad in current state, but I will try to provide the basic algorithm.

    Create class extending from yii\filters\auth\AuthMethod.

    Where to place it it's up to you (because of using namespaces), you can follow your own convention. Let's say we place it in common\components folder.

    You must at least implement authenticate method of AuthInterface (challenge and handleFailure already have default implementations, but you can obviously override them too).

    namespace common\components;
    
    use yii\filters\auth\AuthMethod;
    
    class CustomAuth extends AuthMethod
    {
        /**
         * @inheritdoc
         */
        public function authenticate($user, $request, $response)
        {
            // Put your logic here
        }
    }
    

    Usage in REST controller:

    use common\components\CustomAuth;
    
    ...
    
     /**
      * @inheritdoc
      */
    public function behaviors()
    {
        $behaviors = parent::behaviors();
        $behaviors['authenticator'] = [
            'class' => CustomAuth::className(),            
        ];
    
        return $behaviors;
    }
    

    Also see how built-in auth methods are implemented (HttpBasicAuth, HttpBearerAuth, QueryParamAuth).

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 请问一下这个运行结果是怎么来的
  • ¥15 这个复选框什么作用?
  • ¥15 单通道放大电路的工作原理
  • ¥30 YOLO检测微调结果p为1
  • ¥20 求快手直播间榜单匿名采集ID用户名简单能学会的
  • ¥15 DS18B20内部ADC模数转换器
  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下