2016-03-01 90 views
4

我製作了Yii2 REST API。使用API​​,您可以獲取汽車列表。現在我想使用承載認證來保護API。但我不知道它是如何工作的。Yii2 Rest API承載驗證

首先。我在我的控制器的行爲方法中設置了身份驗證器。

public function behaviors(){ 
    return [ 
     'contentNegotiator' => [ 
      'class' => ContentNegotiator::className(), 
      'formats' => [ 
       'application/json' => Response::FORMAT_JSON, 
      ], 
     ], 
     'authenticator' => [ 
      'class' => CompositeAuth::className(), 
      'authMethods' => [ 
       HttpBearerAuth::className(), 
      ], 
     ] 
    ]; 
} 

這工作得很好。如果我轉到網址,我會收到'未經授權'的信息。

在我的wordpress插件中,我製作了一個函數來使用API​​並使用身份驗證密鑰設置標頭。

function getJSON($template_url) { 
    $authorization = "Authorization: Bearer " . get_option("auth_key"); 

    // Create curl resource 
    $ch = curl_init(); 
    // Set URL 
    curl_setopt($ch, CURLOPT_URL, $template_url); 
    // Return transfer as a string 
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
    // Set headers 
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json', $authorization)); 
    // $output contains output as a string 
    $output = curl_exec($ch); 
    // Close curl resource 
    curl_close($ch); 

    return json_decode($output, true); 
} 

但現在我的問題是。如果此密鑰有效並且給我回復,我如何檢查API?我想搜索數據庫中的密鑰,如果它存在,它也應該給我在同一行中的id或電子郵件。

我不知道如何做到這一點。

+0

那麼每個客戶都應該有他自己的accesstoken?你想使用oauth2? –

回答

5

\yii\filters\auth\HttpBearerAuth::authenticate()就叫\yii\web\User::loginByAccessToken()

$class = $this->identityClass; 
$identity = $class::findIdentityByAccessToken($token, $type); 

所以,你只需要在你的用戶標識類,例如實施findIdentityByAccessToken()

public static function findIdentityByAccessToken($token, $type = null) 
{ 
    return static::findOne(['auth_key' => $token]); 
} 
+0

在這個類中,我使用另一個表,而不是access_tokens的位置。任何想法如何我可以檢查另一個表中的訪問令牌? –

+2

@WouterdenOuden當'findIdentityByAccessToken'返回'null'認證將被拒絕。所以在內部做任何你需要的邏輯(比如檢查標記的有效性),如果認證失敗或者返回一個** user **實例,那麼'Yii :: $ app-> user-> identity'將會持有你可以在你的應用程序中的任何地方使用它。檢查[this](http://www.yiiframework.com/doc-2.0/guide-rest-authentication.html)和[this](http://blog.neattutorials.com/angularjs-and-yii2-part- 2-authentication /)瞭解更多詳情。 –

+0

...您可能還需要構建操作來處理登錄,註冊,...在此示例中(https://github.com/tunecino/Yii2_foundation-apps/tree/master/backend/auth/controllers )。 –