`

OAuth2.0授权学习——1,第三方网站授权

阅读更多

首先下载oauth2.0服务器端库——Oauth2.0,我这里用它已经实现的mongo驱动来演示第三方网站如何申请授权

(当然我们还需要启动mongo服务),下面就用mongo目录里面的例子来测试一下

 

1,申请Client ID(注册一个开发者应用,填写应用ID,Secret以及回调网址)

 

访问

http://localhost/oauth/server/examples/mongo/addclient.php 

 

填写 ID=50021 Secret=rainbow Callback=http://localhost/callback,提交后数据库中生成clients表

 

> db.clients.find()
{ "_id" : "50021", "pw" : "rainbow", "redirect_uri" : "http://localhost/callback" }
 

 

2,引导用户到授权页面授权(资源所有者检查应用的合法性,通过回调网址返回一个token给第三方网站)

 

引导用户访问

http://localhost/oauth/server/examples/mongo/authorize.php?

client_id=50021&

response_type=code

 

(注意这里选择的response_type=code)

我们这里为了简化流程,没有引入用户账户系统,所以没有登录功能,直接点击确认授权。浏览器跳转到

http://localhost/callback?

state=&

code=0d16076aff16ccfe29443cd98f964e22

 

我们就拿到一个临时token,此时查询数据库(包含过期时间和其它选项scope)

 

 

db.auth_codes.find()
{ "_id" : "0d16076aff16ccfe29443cd98f964e22", "client_id" : "50021", "redirect_uri" : "http://localhost/callback", "expires" : 1352687216, "scope" : "" }

 

 

3,第三方网站用这个token去换取access token

 

使用第二步中得到的临时token换取access token,发起请求如下:

http://localhost/oauth/server/examples/mongo/token.php?

code=0d16076aff16ccfe29443cd98f964e22&

client_id=50021&

client_secret=rainbow&

grant_type=authorization_code&

redirect_uri=http://localhost/callback


为了演示方便,这里的请求参数都是通过get方式传递的(修改了一点Oauth2.inc源码),真实的生产环境还是需要通过post方式或者header中携带参数的方式传递,这样会安全很多。

 

服务器返回

 

 

{
    "access_token":"6974c7151aca644b908abe1923c57234",
    "expires_in":3600,
    "scope":null
}

此时查询数据库:

 

 

db.tokens.find()
{ "_id" : "6974c7151aca644b908abe1923c57234", "client_id" : "50021", "expires" : 1352690797, "scope" : null }

 

注:第二步获得的token和access token都有过期时间,可以在OAuth2.inc中配置。

 

4,使用access token访问受限资源

 

访问

http://localhost/oauth/server/examples/mongo/protected_resource.php? oauth_token=6974c7151aca644b908abe1923c57234

 

得到结果“This is a secret.”

 

可以看出OAuth2.0比OAuth1.0版本要简单很多,由于采用了ssl加密,参数对应用层来说都是明文传递,客户端与服务器端都省去了不必要的加密解密工作。

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics