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

如何在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

图片转代码服务由CSDN问答提供 功能建议

我正在尝试遵循Yii2的身份验证教程*,但由于项目的要求,我需要构建自定义身份验证 。 虽然教程确实说明了你可以自己做,但没有详细说明如何。 我需要创建哪些文件以及需要添加到$ behavior ['authenticator']以引用我的自定义身份验证模块的位置和值:

* 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).

    已采纳该答案
    打赏 评论

相关推荐 更多相似问题