Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

手機掃碼登入網頁:Android 二維碼掃描登入的完整實作

編輯:關於 Android 程式設計

用手機掃一下螢幕上的二維碼就完成網頁登入,這個體驗現在很常見。它的原理其實不複雜,核心就是「以二維碼裡的 uuid 作為一座橋」,把手機端已登入的狀態傳回網頁端。

整體流程

1. 網頁端產生二維碼,同時生成一個 uuid 並寫入資料庫;

2. 網頁端持續輪詢,檢查資料庫中該 uuid 是否已有掃描/登入資訊;

3. 手機掃描二維碼取得 uuid,連同使用者帳號密碼一起回傳給伺服器;

4. 伺服器驗證帳密後,把登入資訊寫回該 uuid 對應的紀錄;

5. 網頁端的輪詢查到完整登入資訊,登入成功。

以下示範採用 Java EE(Servlet + Hibernate)搭配 Android 原生掃碼模組的組合。

1. 網頁端

1.1 引入依賴

二維碼的產生交給開源的 QRCode.jar 處理,下載後放入 WEB-INF/lib 即可。

1.2 登入資訊實體類 UserLogin.java

@Entity
@Table(name = "UserLogin")
public class UserLogin {

    @Id
    @GeneratedValue(generator = "UserLoginIdGenerator")
    @GenericGenerator(name = "UserLoginIdGenerator", strategy = "uuid")
    private String id;

    @Column
    private String name;

    @Column
    private String password;

    @Column
    private int uuid;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public int getUuid() {
        return uuid;
    }

    public void setUuid(int uuid) {
        this.uuid = uuid;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}

1.3 產生二維碼 GetQrCodeServlet.java

二維碼的內容刻意設計成一段 JSON,同時帶上後端位址與 uuid,這樣手機端解析起來比較省事。

public class GetQrCodeServlet extends HttpServlet {

    private static final long serialVersionUID = 1L;

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doPost(request, response);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        PrintWriter out = response.getWriter();

        // 產生唯一識別碼
        int uuid = (int) (Math.random() * 100000);

        // 二維碼內容:後端接收位址 + uuid
        JSONObject obj = new JSONObject();
        obj.put("url", "https://192.168.0.199:8080/QrCodeLogin/PhoneLoginServlet");
        obj.put("uuid", uuid);
        String content = obj.toString();
        System.out.println("obj:" + content);

        String imgName = uuid + "_" + (int) (new Date().getTime() / 1000) + ".png";
        String webpath = request.getSession().getServletContext().getRealPath("/");
        String imgPath = webpath + "/img/qrCodeImg/" + imgName;
        String logoPath = webpath + "/img/logo.png";

        QRCodeUtil handler = new QRCodeUtil();
        // 在二維碼中央加上 logo
        handler.encoderQRCode(content, imgPath, logoPath, "png");

        // 把 uuid 存進資料庫,等待手機端回傳登入資訊
        SessionFactory sf = HibernateUtil.getSessionFacotry();
        Session session = sf.openSession();
        session.beginTransaction();
        UserLogin userlogin = new UserLogin();
        userlogin.setUuid(uuid);
        session.save(userlogin);
        session.getTransaction().commit();
        session.close();
        sf = null;

        String qrCodeImg = "https://192.168.0.199:8080/QrCodeLogin/img/qrCodeImg/" + imgName;
        String jsonStr = "{\"uuid\":" + uuid + ",\"qrCodeImg\":\"" + qrCodeImg + "\"}";
        out.print(jsonStr);
        out.flush();
        out.close();
    }
}

1.4 輪詢登入狀態 LongConnectionCheckServlet.java

這裡用「長連接 + 輪詢」的折衷做法:請求進來後在伺服器端迴圈等待,查到結果或逾時才回應,避免前端建立過於頻繁的請求。

public class LongConnectionCheckServlet extends HttpServlet {

    private static final long serialVersionUID = 1L;

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doPost(request, response);
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        int uuid = Integer.parseInt(request.getParameter("uuid"));
        String jsonStr = "";
        long inTime = new Date().getTime();
        Boolean bool = true;

        while (bool) {
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            // 以 uuid 查詢登入表
            String username = "";
            SessionFactory sf = HibernateUtil.getSessionFacotry();
            Session session = sf.openSession();
            Criteria criteria = session.createCriteria(UserLogin.class);
            criteria.add(Restrictions.eq("uuid", uuid));
            List result = criteria.list();

            if (result.size() > 0) {
                for (UserLogin s : result) {
                    username = s.getName();
                    if (!"".equals(username) && username != null) {
                        // 使用者名稱不為空,代表登入成功
                        bool = false;
                        session.clear();
                        session.beginTransaction();
                        session.delete(s); // 刪除紀錄,二維碼即刻失效
                        session.getTransaction().commit();
                    }
                    jsonStr = "{\"uname\":\"" + username + "\"}";
                    System.out.println(username);
                }
            } else {
                // 查不到紀錄,代表二維碼已使用或過期
                if (new Date().getTime() - inTime > 5000) {
                    bool = false;
                }
            }

            session.close();
            sf = null;
        }

        System.out.println("login ok : " + jsonStr);
        PrintWriter out = response.getWriter();
        out.print(jsonStr);
        out.flush();
        out.close();
    }
}

1.5 接收手機回傳 PhoneLoginServlet.java

public class PhoneLoginServlet extends HttpServlet {

    private static final long serialVersionUID = 1L;

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doPost(request, response);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        int uuid = Integer.parseInt(request.getParameter("uuid"));
        String uname = request.getParameter("uname");
        String upwd = request.getParameter("upwd");

        boolean bool = true;     // 是否仍需處理
        boolean islogin = false; // 登入結果

        if (bool) {
            SessionFactory sf = HibernateUtil.getSessionFacotry();
            Session session = sf.openSession();
            Criteria criteria = session.createCriteria(UserLogin.class);
            criteria.add(Restrictions.eq("uuid", uuid));
            List result = criteria.list();

            if (result.size() > 0) {
                for (UserLogin s : result) {
                    s.setName(uname);
                    s.setPassword(upwd);
                    session.clear();
                    session.beginTransaction();
                    session.saveOrUpdate(s);
                    session.getTransaction().commit();
                    bool = false;
                    islogin = true;
                }
            } else {
                // 查無此 uuid,代表二維碼已過期
                islogin = false;
                System.out.println("二維碼已過期,請重新整理頁面");
            }

            session.close();
            sf = null;
        }

        PrintWriter out = response.getWriter();
        out.print(islogin);
        out.flush();
        out.close();
    }
}

1.6 掃碼登入頁面 index.html

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8" />
    <title>掃碼登入</title>
    <script type="text/javascript" src="js/jquery-1.11.0.min.js"></script>
    <style type="text/css">
        .div-content { text-align: center; }
        .img { margin-top: 150px; }
        .div-content-text { text-align: center; margin-top: 20px; font-size: 36px; color: blue; }
    </style>
</head>
<body>
<div class="div-content">
    <img class="img" src="" alt="二維碼" />
    <div class="div-content-text">掃描二維碼登入</div>
</div>
</body>
</html>

1.7 執行結果

2. 手機端

2.1 引入掃碼庫 BarCodeLibrary

掃碼能力來自 zxing 的 Android 移植版本,把 BarCodeLibrary 作為依賴工程引入即可。

2.2 建立工程並加入依賴

2.3 掃碼介面 activity_main.xml

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:gravity="center"
    android:orientation="vertical">

    <Button
        android:id="@+id/btn_scan"
        android:layout_width="120dp"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:background="@android:color/holo_blue_light"
        android:gravity="center"
        android:text="掃碼登錄"
        android:textColor="@android:color/white" />

</LinearLayout>

2.4 MainActivity.java

點擊按鈕後跳進掃碼頁,拿到結果後解析 JSON,取出 uuid 與回傳位址,再用 POST 把帳密送回去。

public class MainActivity extends Activity implements OnClickListener {

    private Button btnScan;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btnScan = (Button) findViewById(R.id.btn_scan);
        btnScan.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        startActivityForResult(new Intent(this, CaptureActivity.class), 0);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            String result = data.getExtras().getString("result");

            JSONObject obj = JSONObject.parseObject(result);
            String uuid = obj.getString("uuid");
            String httpUrl = obj.getString("url");

            HttpUtils http = new HttpUtils();
            RequestParams params = new RequestParams();
            params.addBodyParameter("uuid", uuid);
            params.addBodyParameter("uname", "yangjie");
            params.addBodyParameter("upwd", "123456");

            http.send(HttpRequest.HttpMethod.POST, httpUrl, params, new RequestCallBack() {
                @Override
                public void onFailure(HttpException arg0, String arg1) {
                    Toast.makeText(getApplicationContext(), "登陸失敗,二維碼過期,請重新整理頁面!", 1000).show();
                }

                @Override
                public void onSuccess(ResponseInfo arg0) {
                    Toast.makeText(getApplicationContext(), "登陸成功!", 1000).show();
                }
            });
        }
    }
}

2.5 執行結果

3. 幾個實務上的提醒

這個 Demo 把帳密直接寫在客戶端,僅供理解流程;正式環境應該改成手機端帶著既有的登入 token 去換取網頁端 session,而不是重新輸入一次帳密。

另外,範例中的 uuid 只有六位隨機數,碰撞與被猜到都不難,實作時建議改用更長的隨機字串並加上短效過期機制;輪詢間隔與伺服器端等待時間也需要一起調整,避免佔住過多連線。

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