本人去年在UCLA打醬油的時候曾經要求抓過新浪微博的有關數據。然而要讀寫這些微博信息和朋友關係,必需要在新浪圍脖平臺上註冊應用。也就是要接觸 OAuth 2.0
這個東西。當時基本不懂,今天看到了阮一峯博客上的這篇文章,決定本身動手一試。html
首先,你要把阮一峯博客上的這篇文章 粗略的讀一遍。python
而後你要上 新浪開發平臺 註冊一個應用,我註冊的是微鏈接 - 網頁應用linux
打開界面你能夠看到App Key和App Secret,這是要用的東西git
好,接下來下載新浪微博python SDK,咱們用Python
進行分析github
首先,咱們先根據微博API上面的HOW-TO 文檔上來作web
from weibo import APIClient APP_KEY = '1234567' # app key APP_SECRET = 'abcdefghijklmn' # app secret CALLBACK_URL = 'http://www.example.com/callback' client = APIClient(app_key=APP_KEY, app_secret=APP_SECRET, redirect_uri=CALLBACK_URL) url = client.get_authorize_url()
這樣就拿到了URL了,你打開這個URL一看,正是提示你要受權應用(出現error:redirect_uri_mismatch
同窗請到新浪微博開發界面填好redirect_uri
)json
好,咱們看看源碼vim
class APIClient(object): ''' API client using synchronized invocation. ''' def __init__(self, app_key, app_secret, redirect_uri=None, response_type='code', domain='api.weibo.com', version='2'): self.client_id = str(app_key) self.client_secret = str(app_secret) self.redirect_uri = redirect_uri self.response_type = response_type self.auth_url = 'https://%s/oauth2/' % domain self.api_url = 'https://%s/%s/' % (domain, version) self.access_token = None self.expires = 0.0 self.get = HttpObject(self, _HTTP_GET) self.post = HttpObject(self, _HTTP_POST) self.upload = HttpObject(self, _HTTP_UPLOAD) def get_authorize_url(self, redirect_uri=None, **kw): ''' return the authorization url that the user should be redirected to. ''' redirect = redirect_uri if redirect_uri else self.redirect_uri if not redirect: raise APIError('21305', 'Parameter absent: redirect_uri', 'OAuth2 request') response_type = kw.pop('response_type', 'code') return '%s%s?%s' % (self.auth_url, 'authorize', \ _encode_params(client_id = self.client_id, \ response_type = response_type, \ redirect_uri = redirect, **kw))
client_id
,redirect_url
,app_key
,好熟悉啊,仔細一看,原來是受權碼模式的第一步api
The client constructs the request URI by adding the following
parameters to the query component of the authorization endpoint URI
using the "application/x-www-form-urlencoded" format, per Appendix B:瀏覽器response_type
REQUIRED. Value MUST be set to "code".client_id
REQUIRED. The client identifier as described in Section 2.2.redirect_uri
OPTIONAL. As described in Section 3.1.2.scope
OPTIONAL. The scope of the access request as described by
Section 3.3.state
RECOMMENDED. An opaque value used by the client to maintain
state between the request and callback. The authorization
server includes this value when redirecting the user-agent back
to the client. The parameter SHOULD be used for preventing
cross-site request forgery as described in Section 10.12.
好了,當咱們把帳號密碼填寫好了以後驗證成功後,你發現你的瀏覽器上面的URL發生了變化,究竟是這麼回事呢,請看第二步Authorization Response
If the resource owner grants the access request, the authorization
server issues an authorization code and delivers it to the client by
adding the following parameters to the query component of the
redirection URI using the "application/x-www-form-urlencoded" format,
per Appendix B:code
REQUIRED. The authorization code generated by the
authorization server. The authorization code MUST expire
shortly after it is issued to mitigate the risk of leaks. A
maximum authorization code lifetime of 10 minutes is
RECOMMENDED. The client MUST NOT use the authorization code more than once. If an authorization code is used more than
once, the authorization server MUST deny the request and SHOULD
revoke (when possible) all tokens previously issued based on
that authorization code. The authorization code is bound to
the client identifier and redirection URI.state
REQUIRED if the "state" parameter was present in the client
authorization request. The exact value received from the
client.For example, the authorization server redirects the user-agent by
sending the following HTTP response:
HTTP/1.1 302 Found Location: https://client.example.com/cb?code=SplxlOBeZQQYbYS6WxSbIA &state=xyz
而後咱們繼續按照API的指示作
# 獲取URL參數code: code = your.web.framework.request.get('code') r = client.request_access_token(code) def request_access_token(self, code, redirect_uri=None): redirect = redirect_uri if redirect_uri else self.redirect_uri if not redirect: raise APIError('21305', 'Parameter absent: redirect_uri', 'OAuth2 request') r = _http_post('%s%s' % (self.auth_url, 'access_token'), \ client_id = self.client_id, \ client_secret = self.client_secret, \ redirect_uri = redirect, \ code = code, grant_type = 'authorization_code') return self._parse_access_token(r)
這個得到code
方法一般能夠有不少,可是咱們既然是實驗,就手動複製code
吧。
哈哈,很明顯request_access_token
這個方法就是發一個HTTP POST
包嘛
第三步Access Token Request
The client makes a request to the token endpoint by sending the
following parameters using the "application/x-www-form-urlencoded"
format per Appendix B with a character encoding of UTF-8 in the HTTP
request entity-body:grant_type
REQUIRED. Value MUST be set to "authorization_code".code
REQUIRED. The authorization code received from the
authorization server.redirect_uri
REQUIRED, if the "redirect_uri" parameter was included in the
authorization request as described in Section 4.1.1, and their
values MUST be identical.client_id
REQUIRED, if the client is not authenticating with the
authorization server as described in Section 3.2.1.If the client type is confidential or the client was issued client
credentials (or assigned other authentication requirements), the
client MUST authenticate with the authorization server as described
in Section 3.2.1.For example, the client makes the following HTTP request using TLS
(with extra line breaks for display purposes only):POST /token HTTP/1.1 Host: server.example.com Authorization: Basic czZCaGRSa3F0MzpnWDFmQmF0M2JW Content-Type: application/x-www-form-urlencoded grant_type=authorization_code&code=SplxlOBeZQQYbYS6WxSbIA &redirect_uri=https%3A%2F%2Fclient%2Eexample%2Ecom%2Fcb
最後一步
access_token = r.access_token # 新浪返回的token,相似abc123xyz456 expires_in = r.expires_in # token過時的UNIX時間:http://zh.wikipedia.org/wiki/UNIX%E6%97%B6%E9%97%B4 # TODO: 在此可保存access token client.set_access_token(access_token, expires_in)
就是從服務器返回的HTTP
包中解析access_token
和 expire_in
數據
一樣來看RFC
文檔中寫的
If the access token request is valid and authorized, the
authorization server issues an access token and optional refresh
token as described in Section 5.1. If the request client
authentication failed or is invalid, the authorization server returns
an error response as described in Section 5.2.An example successful response:
HTTP/1.1 200 OK Content-Type: application/json;charset=UTF-8 Cache-Control: no-store Pragma: no-cache { "access_token":"2YotnFZFEjr1zCsicMWpAA", "token_type":"example", "expires_in":3600, "refresh_token":"tGzv3JOkF0XG5Qx2TlKWIA", "example_parameter":"example_value" }
接下來就能夠調用API啦~
對於最後兩步看的很累的話,能夠本身嘗試寫一個
import urllib, urllib2 APP_KEY = '2613134348' APP_SECRET = '5a14f41598a7444c7e0dc0422519b091' # app secret ACCESS_TOKEN = '9cd1b3869e62491331caf444456953e8' data = { 'grant_type' : 'authorization_code', 'code' :ACCESS_TOKEN, 'redirect_uri':'http://www.ceclinux.org', 'client_id':APP_KEY, 'client_secret':APP_SECRET } headers = {'host':'api.weibo.com','Authorization':'OAuth2 %s' % ACCESS_TOKEN} data = urllib.urlencode(data) request = urllib2.Request('https://api.weibo.com/oauth2/access_token', data, headers) response = urllib2.urlopen(request) print response.read()
運行這個文件
最後也能獲得一個包含access_token
和expire_date
的JSON文件
沒了~