[英]yii2: Authentification in rest api (yii\rest\Controller)
對於我的休息api,我使用yii\\rest\\Controller
class TweetController extends Controller
{
public function behaviors()
{
$behaviors = parent::behaviors();
$behaviors['authenticator'] = [
'class' => HttpBasicAuth::className(),
'auth' => [$this, 'auth']
];
$behaviors['contentNegotiator'] = [
'class' => ContentNegotiator::className(),
'formats' => [
'application\json' => Response::FORMAT_JSON,
]
];
return $behaviors;
}
// not solved yet
public function auth($pass)
{}
/**
* @param int $count
*
* @return array
* @throws \yii\base\InvalidConfigException
*/
public function actionLastTweets($count = 10)
{
/**
* @var TweetLastfinder $tweetLastFinder
*/
$tweetLastFinder = Yii::$app->get('tweetlastfinder');
return $tweetLastFinder->findLastTweets($count);
}
我也使用prettyUrls 'GET tweet/last-tweets/<count>' => 'tweet/last-tweets'
actionLastTweets返回將其轉換為json的數組。
想法只是認證。 在docs中是如何在模型中實現IdentityInterface的示例。 但我不直接與AR合作。 我認為。 我需要正確編寫auth()方法。
我不明白,通過身份驗證時應該從auth()返回值嗎? 以及如何按要求發送? (我的意思是http://localhost/index.php/tweet/last-tweets/50
沒有身份驗證,它是如何改變的?)
為簡單起見,有一個字符串值$ password ='qwerty',我想檢查參數$ pass是否等於$ password - 驗證通過
某種程度的:
public function auth($pass)
{
$password = 'qwerty';
if ($pass == $password) {
authentication passed
} else {
authentication failed
}
}
身份驗證的主題是您的身份(aka用戶)必須實現功能findIdentityByAccessToken
參見\\ yii \\ web \\ IdentityInterface
要在命令行上嘗試API,可以按如下方式使用cUrl(令牌:XXXXXXXX_accessTokenString_XXXXXX)
注意,“:”在基本的身份驗證中將用戶與密碼分開, 令牌用作用戶
將JSON POST到MessageController(復數不是錯誤)
curl --user "XXXXXXXX_accessTokenString_XXXXXX:" -H "Accept:application/json" -H "Content-Type:application/json" -XPOST "http://rest.my-domain.com/messages" -d '{"email": "me@example.com"}'
將JSON發布到UserController啟用xdebug
curl --user "XXXXXXXX_accessTokenString_XXXXXX:" --cookie 'XDEBUG_SESSION=1221221' -H "Accept:application/json" -H "Content-Type:application/json" -XPOST "http://rest.my-domain.com/messages" -d '{"email": "me@example.com"}'
GETJSON到UserController啟用xdebug
curl --user "XXXXXXXX_accessTokenString_XXXXXX:" -H "Accept:application/json" -H "Content-Type:application/json" -XGET "http://rest.my-domain.com/messages/123"
另請參見Yii2 REST服務指南http://www.yiiframework.com/doc-2.0/guide-rest-quick-start.html
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.