2016-04-11 74 views
0

HI我剛剛發現Yii框架和我需要一些指導方針來實現這個...Yii2 - 如何在RESTful API中實現RBAC授權?

Yii2 RBAC - Official Guide

...在我的RESTful應用程序。我知道我必須override方法[checkAccess][3]()在我的控制器中,但我找不到任何示例。我的API具有基於令牌的Beare身份驗證,會話被禁用(無狀態)。

+2

使用RBAC如常。如果您發送正確的令牌,您將擁有用戶身份。 – SiZE

+0

@SiZE明白了!謝謝! – JJPunch

回答

0

在你的控制器:

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; 
    } 
+0

這不是一個好的答案,請告訴更多關於代碼或解析的信息。 – aidinMC