Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發實例

微博服務端 API 的 OAuth 認證實作詳解

編輯:Android 開發實例

新浪微博與 update 相關的 API 掛了許多天遲遲未恢復,一直回傳錯誤:40070 Error limited application access api!。開放平台論壇裡一大堆人都在等它恢復,官方卻連個公告都沒有,既不說明原因也不提恢復時間,實在令人無奈。原本還傳言 API 正在升級、週一就會恢復,結果到了週二依然故我。基於這個原因,我的 Android 版新浪微博客戶端已經停工好幾天,卡住的正是與 update 相關的功能。

客戶端做不下去,就轉頭自己做服務端程式,提供類似新浪微博 REST API 的服務。API 說穿了並不難,不外乎透過連結對外提供 json 或 xml 格式的資料,並接收外部傳入的資料進行儲存、刪除、更新等操作。整個過程最麻煩的莫過於 OAuth 認證。先前做 Android 客戶端時,我曾花不少時間研究 OAuth,一開始採用 oauth-signpost 這個開源專案,後來基於某些原因放棄,改為自己實作。現在回頭做服務端的 OAuth,其實原理與客戶端相通:客戶端對參數字串進行簽名並把簽名值傳到服務端,服務端再用同樣方式對參數字串簽名,然後比對兩者是否一致。想深入了解的讀者,不妨搜尋 OAuth 的相關資料。

服務端程式我用 ASP.NET 和 C# 撰寫,而非 Java,理由很單純——我對 .NET 更熟悉。為了快速見效,這次採用 oauth-dot-net 開源專案,並非全部自己實作。

一、建立專案與加入參考

首先建立名為 Rest Api 的 ASP.NET Web 應用程式,然後加入 oauth-dot-net 相關的幾個 dll:Castle.Core.dll、Castle.MicroKernel.dll、Castle.Windsor.dll、CommonServiceLocator.WindsorAdapter.dll、Microsoft.Practices.ServiceLocation.dll、OAuth.Net.Common.dll、OAuth.Net.Components.dll、OAuth.Net.ServiceProvider.dll。

二、設定 Web.config 與 Global.asax

在 Web.config 中加入相應設定(可參考 OAuth.Net.Examples.EchoServiceProvider 專案),並在 Global.asax.cs 加入:

public override void Init()
{
    IServiceLocator injector =
        new WindsorServiceLocator(
            new WindsorContainer(
                new XmlInterpreter(
                    new ConfigResource("oauth.net.components"))));
    ServiceLocator.SetLocatorProvider(() => injector);
}

接下來是重點,也就是 request_token、authorize、access_token 三個環節的實作,這是 OAuth 認證的核心流程,具體實作多半參考 OAuth.Net.Examples.EchoServiceProvider 範例。

三、ConsumerStore.cs:儲存 Consumer 資訊

這個類別用來儲存 Consumer 資訊。由於是測試專案,這裡先存在記憶體中,實際專案應把 Consumer 資訊存入資料庫。Consumer 對應到新浪微博,其實就是應用的 App Key 與 App Secret;開發者在新浪微博建立新應用後即可取得。完整的做法還應提供一個讓第三方開發者申請 App Key 與 App Secret 的頁面,這裡就直接寫死一個名為「測試應用」的 Consumer 供客戶端測試:

public sealed class ConsumerStore : InMemoryConsumerStore, IConsumerStore
{
    internal static readonly IConsumer FixedConsumer = new OAuthConsumer("2433927322", "87f042c9e8183cbde0f005a00db1529f", "測試應用", ConsumerStatus.Valid);
    public ConsumerStore()
    {
        this.ConsumerDictionary.Add(ConsumerStore.FixedConsumer.Key, ConsumerStore.FixedConsumer);
    }
    public override bool Add(IConsumer consumer) { throw new NotSupportedException("固定 store,不可新增。"); }
    public override bool Contains(string consumerKey) { return ConsumerStore.FixedConsumer.Key.Equals(consumerKey); }
    public override bool Update(IConsumer consumer) { throw new NotSupportedException("固定 store,不可更新。"); }
    public override bool Remove(IConsumer consumer) { throw new NotSupportedException("固定 store,不可移除。"); }
}

四、RequestTokenHandler.cs:request_token

這個類別繼承自 OAuth.Net.ServiceProvider.RequestTokenHandler,屬於 httpHandler,因此需在 Web.config 註冊。它負責接收客戶端請求,回傳 Request Token 與 Request Secret:

public sealed class RequestTokenHandler : OAuth.Net.ServiceProvider.RequestTokenHandler
{
    protected override void IssueRequestToken(HttpContext httpContext, OAuthRequestContext requestContext)
    {
        IRequestToken token = this.GenerateRequestToken(httpContext, requestContext);
        requestContext.RequestToken = token;
        Uri callbackUri;
        if (Uri.TryCreate(requestContext.Parameters.Callback, UriKind.Absolute, out callbackUri))
        {
            if (!ServiceProviderContext.CallbackStore.ContainsCallback(token))
            {
                ServiceProviderContext.CallbackStore.AddCallback(token, callbackUri);
            }
        }
        else
        {
            OAuthRequestException.ThrowParametersRejected(new string[] { Constants.CallbackParameter }, "Not a valid Uri.");
        }
        requestContext.ResponseParameters[Constants.TokenParameter] = token.Token;
        requestContext.ResponseParameters[Constants.TokenSecretParameter] = token.Secret;
    }
    protected override IRequestToken GenerateRequestToken(HttpContext httpContext, OAuthRequestContext requestContext)
    {
        return ServiceProviderContext.TokenGenerator.CreateRequestToken(requestContext.Consumer, requestContext.Parameters);
    }
}

五、authorize.aspx:授權頁面

建立 authorize.aspx 作為使用者輸入帳號密碼進行授權的頁面。它會把使用者輸入的帳密與資料庫中的紀錄比對,驗證通過後便導回先前客戶端提供的 callback 位址,並附上一組驗證碼:

public partial class authorize : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e) { }
    protected void Button1_Click(object sender, EventArgs e)
    {
        if (loginName.Text == "test" && password.Text == "123")
        {
            string toke = Request.Params["oauth_token"];
            IRequestToken tk = ServiceProviderContext.TokenStore.GetRequestToken(toke);
            Uri callback = ServiceProviderContext.CallbackStore.GetCalback(tk);
            string oauth_verifier = ServiceProviderContext.VerificationProvider.Generate(tk);
            Response.Redirect(callback.ToString() + "?oauth_verifier=" + oauth_verifier);
        }
    }
}

六、AccessTokenHandler.cs:access_token

同樣是 httpHandler,需在 Web.config 註冊,負責接收客戶端請求並回傳 Access Token 與 Access Secret:

public sealed class AccessTokenHandler : OAuth.Net.ServiceProvider.AccessTokenHandler
{
    protected override void IssueAccessToken(HttpContext httpContext, OAuthRequestContext requestContext)
    {
        IAccessToken accessToken = this.GenerateAccessToken(httpContext, requestContext);
        accessToken.Status = TokenStatus.Authorized;
        requestContext.ResponseParameters[Constants.TokenParameter] = accessToken.Token;
        requestContext.ResponseParameters[Constants.TokenSecretParameter] = accessToken.Secret;
    }
    protected override IAccessToken GenerateAccessToken(HttpContext httpContext, OAuthRequestContext requestContext)
    {
        return ServiceProviderContext.TokenGenerator.CreateAccessToken(requestContext.Consumer, requestContext.RequestToken);
    }
}

並搭配 TokenGenerator 與 TokenStore 來產生與保存 token:

public class TokenGenerator : ITokenGenerator
{
    internal static readonly IRequestToken FixedRequestToken = new OAuthRequestToken("requestkey", "requestsecret",
        ConsumerStore.FixedConsumer, TokenStatus.Authorized, null,
        ServiceProviderContext.DummyIdentity, new string[] { });
    internal static readonly IAccessToken FixedAccessToken = new OAuthAccessToken("accesskey", "accesssecret",
        ConsumerStore.FixedConsumer, TokenStatus.Authorized, TokenGenerator.FixedRequestToken);
    public IRequestToken CreateRequestToken(IConsumer consumer, OAuthParameters parameters) { return TokenGenerator.FixedRequestToken; }
    public IAccessToken CreateAccessToken(IConsumer consumer, IRequestToken requestToken) { return TokenGenerator.FixedAccessToken; }
}

如此一來,一個最簡單的小型服務端 OAuth 認證就完成了,接著用 Android 客戶端測試即可通過。

注意事項

一、Android 模擬器存取本機服務時,位址為 10.0.2.2。例如 https://localhost:3423/authorize.aspx 在模擬器中要寫成 https://10.0.2.2:3423/authorize.aspx。

二、OAuth.Net 類庫的 ICallbackStore 介面需補上一個 Uri GetCalback(IRequestToken token);,並在 InMemoryCallbackStore 中實作:

public Uri GetCalback(IRequestToken token)
{
    lock (this.callbackStore)
    {
        if (this.callbackStore.ContainsKey(token))
        {
            return this.callbackStore[token];
        }
        else
        {
            return null;
        }
    }
}

三、為了沿用先前寫的新浪 Android 客戶端,需修改 AccessTokenHandler 的 ParseParameters 方法。因為新浪呼叫 API 時都會帶一個 source 參數,所以要把它加入允許清單:

protected virtual void ParseParameters(HttpContext httpContext, OAuthRequestContext requestContext)
{
    ......
    parameters.AllowOnly(
        Constants.ConsumerKeyParameter,
        Constants.TokenParameter,
        Constants.SignatureMethodParameter,
        Constants.SignatureParameter,
        Constants.TimestampParameter,
        Constants.NonceParameter,
        Constants.VerifierParameter,
        Constants.VersionParameter,   // (optional)
        Constants.RealmParameter,     // (optional)
        "source");
    ......
}
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved