實現原理:
1、web登錄頁面,利用jquery.qrcode展示一個隨機生成的登錄碼的二維碼;
2、手機App掃描二維碼取得登錄碼;
3、手機App將本地用戶id+登錄碼通過api提交服務器;
4、服務器api,收到手機App請求,根據用戶id+登錄碼,修改用戶信息,同時將用戶id+登錄碼廣播;
5、web登錄頁面收到用戶id+登錄碼,先本地驗證登錄碼是否一致,然后向服務器驗證用戶id+登錄碼,驗證成功跳轉到指定頁面。
6、完成掃碼登錄。
模擬web登錄頁面代碼:
<!doctype html>
<html lang="en"><head><meta charset="UTF-8"><meta name="Generator" content="EditPlus?"><meta name="Author" content=""><meta name="Keywords" content=""><meta name="Description" content=""><title>掃碼登錄測試</title></head><body><script src="http://***/Scripts/jquery-1.10.2.min.js"></script><script src="http://***/Scripts/jquery.signalR-2.4.1.min.js"></script><script src="http://***/Scripts/jquery.qrcode.min.js"></script><script src="http://***/Signalr/hubs"></script><div id="qrcode"><canvas width="256" height="256"></canvas></div><script type="text/javascript">jQuery.support.cors=true;var SignalrHub=$.connection.hub;$(function(){var loginCode=guid();//生成登錄碼二維碼jQuery('#qrcode').qrcode(loginCode);console.log(loginCode);SignalrHub.url="http://***/Signalr/hubs";//服務器端Singnalr hub 路徑var hubClient=$.connection.messageHub.client;hubClient.ShowMessage=function(msg){var jsonMsg= $.parseJSON(msg);if(jsonMsg && jsonMsg.loginCode==loginCode){//向服務器驗證用戶id+登錄碼if(server.CheckLoginCode(jsonMsg.UserId,jsonMsg.loginCode)){alert("登錄成功!");top.location.reload();//跳轉到需要的頁面}}}SignalrHub.start();//SignalrHub.stop()});//生成仿Guid字符串function guid() {return 'ecbxxxxx-xxxx-xxxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);return v.toString(16);});}</script></body>
</html>
?
模擬服務器代碼:
//app設置用戶登錄碼接口
public string SetLoginCode(string userId,string loginCode)
{ //todo 設置登錄碼//廣播消息var hub = GlobalHost.ConnectionManager.GetHubContext<MessageHub>();hub.Clients.All.ShowMessage(userId+loginCode);//也可以定向廣播
}//web驗證登錄碼接口
public bool CheckLoginCode(string userId,string loginCode)
{ //todo 驗證登錄碼//todo 驗證成功 清除或者更改登錄碼return true;
}
?
服務器如何使用Signalr?請參閱相關文檔 https://blog.csdn.net/admans/article/details/89309761。