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

Android 對接 IIS 表單驗證的完整實作

編輯:Android 開發實例

設計思路

Android 用戶端存取架在 IIS 上的 ASP.NET 服務時,若尚未登入,ASP.NET 的 Form 整合驗證會把我們導向登入頁。輸入正確的帳號密碼後,才能進入主程式。

本案例中,用戶端與伺服器之間一律以 JSON 傳遞資料,用戶端再依回傳內容的欄位判斷目前的登入狀態。由於 Form 驗證的機制是把狀態存在 Cookie 裡,所以每次發出 HTTP 請求前,都必須先把上一次的 Cookie 帶上去。

一、伺服器端:ASP.NET MVC

先建立一個統一格式的回應 Model,因為每個請求都會回傳 JSON:

public class ResponseResult
{
    /// <summary> 是否已登入 </summary>
    public bool IsAuthenticated { get; set; }

    /// <summary> 是否執行成功 </summary>
    public bool IsSuccess { get; set; }

    /// <summary> 登入帳號 </summary>
    public string Identity { get; set; }

    /// <summary> 執行結果訊息 </summary>
    public object Result { get; set; }
}

HomeController 的三個 Action

Index 是需要通過驗證才能存取的 Action,加上 [Authorize] 標記;LogOn 是未登入時被導向的 Action;Register 則是登入 Action,帳密正確時寫入 Form 驗證 Cookie。

public class HomeController : Controller
{
    [Authorize]
    public ActionResult Index()
    {
        return Json(new ResponseResult
        {
            Result = "登入成功",
            IsAuthenticated = true,
            IsSuccess = true,
            Identity = this.User.Identity.Name
        }, "text/html", JsonRequestBehavior.AllowGet);
    }

    public ActionResult LogOn()
    {
        return Json(new ResponseResult
        {
            Result = "您尚未登入",
            IsSuccess = true
        }, "text/html", JsonRequestBehavior.AllowGet);
    }

    public ActionResult Register(string account, string password)
    {
        if (account == "demo" && password == "123")
        {
            FormsAuthentication.SetAuthCookie(account, false);
            return Json(new ResponseResult
            {
                Result = "登入成功",
                IsSuccess = true,
                IsAuthenticated = true,
                Identity = account
            }, "text/html", JsonRequestBehavior.AllowGet);
        }
        return Json(new ResponseResult
        {
            Result = "帳號或密碼錯誤"
        }, "text/html", JsonRequestBehavior.AllowGet);
    }
}

Web.config 設定

<authentication mode="Forms">
    <forms loginUrl="~/Home/LogOn" timeout="2880" />
</authentication>

最後設定 IIS 並部署這個 MVC 網站。

二、用戶端:Cookie 的保存與重用

整個用戶端的關鍵就在這個 HttpHelper。它做三件事:發請求、把回應讀成字串、在請求前後保存與附加 Cookie。

public abstract class HttpHelper {

    private final static String TAG = "HttpHelper";
    private final static String SERVER_URL = "https://192.168.1.104:180/Home/";

    private static CookieStore cookieStore;

    public static String invoke(String actionName, List<NameValuePair> params) {
        String result = null;
        try {
            String url = SERVER_URL + actionName + "/";
            HttpPost httpPost = new HttpPost(url);

            if (params != null && params.size() > 0) {
                HttpEntity entity = new UrlEncodedFormEntity(params, "UTF-8");
                httpPost.setEntity(entity);
            }

            DefaultHttpClient httpClient = new DefaultHttpClient();

            // 請求前:把上次保存的 Cookie 帶上去
            if (cookieStore != null) {
                httpClient.setCookieStore(cookieStore);
            }

            HttpResponse httpResponse = httpClient.execute(httpPost);

            StringBuilder builder = new StringBuilder();
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    httpResponse.getEntity().getContent()));
            for (String s = reader.readLine(); s != null; s = reader.readLine()) {
                builder.append(s);
            }
            result = builder.toString();

            // 請求後:保存本次的 Cookie 供下次使用
            cookieStore = ((AbstractHttpClient) httpClient).getCookieStore();
        } catch (Exception e) {
            Log.e(TAG, e.toString());
        }
        return result;
    }

    public static String invoke(String actionName) {
        return invoke(actionName, null);
    }
}

這個設計的重點:Cookie 必須是全域的,每次呼叫前附加、呼叫後保存,登入狀態才能跨請求延續。

三、登入與主畫面

兩個 Activity 都使用 AsyncTask 把網路請求移出 UI 執行緒,並在 onPreExecute() 顯示進度對話框、在 onPostExecute() 解析 JSON 並更新介面。

// 登入:送出帳密,成功後跳轉主畫面
protected String doInBackground(Void... arg0) {
    String account = edtAccount.getText().toString();
    String password = edtPassword.getText().toString();
    List<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair("account", account));
    params.add(new BasicNameValuePair("password", password));
    return HttpHelper.invoke("Register", params);
}

// 主畫面:呼叫需要驗證的 Index,依 IsAuthenticated 判斷狀態
protected String doInBackground(Void... arg0) {
    return HttpHelper.invoke("Index");
}

在 onPostExecute() 中,登入頁依 IsSuccess 決定是否跳轉;主畫面則依 IsAuthenticated 決定顯示身份資訊,或跳回登入頁。

最後別忘了在 AndroidManifest.xml 加上網路權限:

<uses-permission android:name="android.permission.INTERNET" />

整套機制的核心其實只有一句話:Form 驗證靠 Cookie 維持狀態,所以用戶端必須自己管好 Cookie 的生命週期。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved