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 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?