Yii2 - 如何在RESTful API中实现RBAC授权?

时间:2016-04-11 18:02:18

标签: api rest yii2 authorization rbac

我刚刚发现了Yii框架,我需要一些指导来实现这个......

Yii2 RBAC - Official Guide

...在我的RESTful应用中。我知道我必须override我的控制器中的方法[checkAccess][3](),但我找不到任何示例。我的API具有基于令牌的Beare身份验证,会话被禁用(无状态)。

1 个答案:

答案 0 :(得分:1)

在您的控制器中:

public function behaviors()
    {
        $behaviors = parent::behaviors();

        $behaviors['authenticator'] = [
            'class' => CompositeAuth::className(),
            'authMethods' => [
                HttpBearerAuth::className(),
            ],
        ];

        // add CORS filter
        $behaviors['corsFilter'] = [
            'class' => Cors::className(),
            'cors' => [
                'Origin' => ['*'],
                'Access-Control-Request-Method' => ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
                'Access-Control-Request-Headers' => ['*'],
            ],
        ];

        // avoid authentication on CORS-pre-flight requests (HTTP OPTIONS method)
        $behaviors['authenticator']['except'] = ['options', 'login', 'signup'];

        $behaviors['access'] = [
            'class' => AccessControl::className(),
            'only' => [
                'update',
                'delete',
                'view',
                'index',
            ],
            'rules' => [
                [
                    'actions' => [
                        'update',
                        'delete',
                        'view',
                        'index',
                    ],
                    'allow' => true,
                    'roles' => ['@'],
                ],
            ],
        ];

        $behaviors['verbFilter'] = [
            'class' => VerbFilter::className(),
            'actions' => [
                'signup' => ['POST'],
                'login' => ['POST'],
                'update' => ['PUT'],
                'delete' => ['DELETE'],
                'view' => ['GET'],
                'index' => ['GET'],
            ],
        ];

        return $behaviors;
    }