dongwende1984 2015-03-16 21: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-16 21: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).

    展开全部

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

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部