2016-03-01 75 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 )。 –