对于没有服务端的第三方应用,使用账号密码授权也是一种方式(不过需要基于用户对这个应用足够信任的前提)
1,申请Client ID(填写应用ID号和密码,这里不需要填写回调网址)
访问
http://localhost/oauth/server/examples/mongo/addclient.php
填写ID=50001,Secret=pwd提交,查询数据库如下
> db.clients.find() { "_id" : "50001", "pw" : "pwd", "redirect_uri" : "" }
2,直接使用用户账号,密码获取access token
发起请求如下
http://localhost/oauth/server/examples/mongo/token.php?
client_id=50001&
client_secret=pwd&
grant_type=password&
username=ciaos&
password=ciaospwd
返回
{ "access_token":"1efd8b9a68de73934d9dd9218fff899f", "expires_in":3600, "scope":null }
查询数据库如下
> db.tokens.find() { "_id" : "1efd8b9a68de73934d9dd9218fff899f", "client_id" : "50001", "expires" : 1352693889, "scope" : null }
当然服务器端需要支持这种授权机制,我们需要在MongoOAuth中重载OAuth2这个类的相关函数如下:
/** * Overrides OAuth2::getSupportedGrantTypes(). */ protected function getSupportedGrantTypes() { return array( OAUTH2_GRANT_TYPE_AUTH_CODE, OAUTH2_GRANT_TYPE_USER_CREDENTIALS ); }
以及判断用户账号密码的逻辑
/** * Implements OAuth2::checkClientCredentials(). * */ protected function checkUserCredentials($client_id, $username, $password) { //check whether account information is correct if(!($username == "ciaos" && $password == "ciaospwd")){ return false; } //check whether it's a valid client $client = $this->db->clients->findOne(array("_id" => $client_id)); return $client !== NULL; }
这样我们就可以用第二步获取到的access token直接访问受限资源了,访问方法和网站授权一样,不再介绍。