日韩无码专区无码一级三级片|91人人爱网站中日韩无码电影|厨房大战丰满熟妇|AV高清无码在线免费观看|另类AV日韩少妇熟女|中文日本大黄一级黄色片|色情在线视频免费|亚洲成人特黄a片|黄片wwwav色图欧美|欧亚乱色一区二区三区

RELATEED CONSULTING
相關咨詢
選擇下列產(chǎn)品馬上在線溝通
服務時間:8:30-17:00
你可能遇到了下面的問題
關閉右側(cè)工具欄

新聞中心

這里有您想知道的互聯(lián)網(wǎng)營銷解決方案
如何實現(xiàn)Web端指紋登錄

前言

現(xiàn)在越來越多的筆記本電腦內(nèi)置了指紋識別,用于快速從鎖屏進入桌面,一些客戶端的軟件也支持通過指紋來認證用戶身份。

網(wǎng)站建設哪家好,找創(chuàng)新互聯(lián)!專注于網(wǎng)頁設計、網(wǎng)站建設、微信開發(fā)、小程序定制開發(fā)、集團企業(yè)網(wǎng)站建設等服務項目。為回饋新老客戶創(chuàng)新互聯(lián)還提供了玉環(huán)免費建站歡迎大家使用!

前幾天我在想,既然客戶端軟件能調(diào)用指紋設備,web端應該也可以調(diào)用,經(jīng)過一番折騰后,終于實現(xiàn)了這個功能,并應用在了我的開源項目中。

本文就跟大家分享下我的實現(xiàn)思路以及過程,歡迎各位感興趣的開發(fā)者閱讀本文。

實現(xiàn)思路

瀏覽器提供了Web Authentication API, 我們可以利用這套API來調(diào)用用戶的指紋設備來實現(xiàn)用戶信息認證。

https://developer.mozilla.org/zh-CN/docs/Web/API/Web_Authentication_API

注冊指紋

首先,我們需要拿到服務端返回的用戶憑證,隨后將用戶憑證傳給指紋設備,調(diào)起系統(tǒng)的指紋認證,認證通過后,回調(diào)函數(shù)會返回設備id與客戶端信息,我們需要將這些信息保存在服務端,用于后面調(diào)用指紋設備來驗證用戶身份,從而實現(xiàn)登錄。

接下來,我們總結(jié)下注冊指紋的過程,如下所示:

  •  用戶使用其他方式在網(wǎng)站登錄成功后,服務端返回用戶憑證,將用戶憑證保存到本地
  •  檢測客戶端是否存在指紋設備
  •  如果存在,將服務端返回的用戶憑證與用戶信息傳遞給指紋注冊函數(shù)來創(chuàng)建指紋
  •  身份認證成功,回調(diào)函數(shù)返回設備id與客戶端信息,將設備id保存到本地
  •  將設備id與客戶端信息發(fā)送至服務端,將其存儲到指定用戶數(shù)據(jù)中。

注意:注冊指紋只能工作在使用 https 連接,或是使用 localhost的網(wǎng)站中。

指紋認證

用戶在我們網(wǎng)站授權指紋登錄后,會將用戶憑證與設備id保存在本地,當用戶進入我們網(wǎng)站時,會從本地拿到這兩條數(shù)據(jù),提示它是否需要通過指紋來登錄系統(tǒng),同意之后則將設備id與用戶憑證傳給指紋設備,調(diào)起系統(tǒng)的指紋認證,認證通過后,調(diào)用登錄接口,獲取用戶信息。

接下來,我們總結(jié)下指紋認證的過程,如下所示:

  •  從本地獲取用戶憑證與設備id
  •  檢測客戶端是否存在指紋設備
  •  如果存在,將用戶憑證與設備id傳給指紋認證函數(shù)進行校驗
  •  身份認證成功,調(diào)用登錄接口獲取用戶信息

注意:指紋認證只能工作在使用 https 連接,或是使用 localhost的網(wǎng)站中。

實現(xiàn)過程

上一個章節(jié),我們捋清了指紋登錄的具體實現(xiàn)思路,接下來我們來看下具體的實現(xiàn)過程與代碼。

服務端實現(xiàn)

首先,我們需要在服務端寫3個接口:獲取TouchID、注冊TouchID、指紋登錄

獲取TouchID

這個接口用于判斷登錄用戶是否已經(jīng)在本網(wǎng)站注冊了指紋,如果已經(jīng)注冊則返回TouchID到客戶端,方便用戶下次登錄。

  •  controller層代碼如下
 
 
 
 
  1. @ApiOperation(value = "獲取TouchID", notes = "通過用戶id獲取指紋登錄所需憑據(jù)") 
  2.   @CrossOrigin() 
  3.   @RequestMapping(value = "/getTouchID", method = RequestMethod.POST) 
  4.   public ResultVO getTouchID(@ApiParam(name = "傳入userId", required = true) @Valid @RequestBody GetTouchIdDto touchIdDto, @RequestHeader(value = "token") String token) {
  5.        JSONObject result = userService.getTouchID(JwtUtil.getUserId(token)); 
  6.       if (result.getEnum(ResultEnum.class, "code").getCode() == 0) { 
  7.           // touchId獲取成功 
  8.           return ResultVOUtil.success(result.getString("touchId")); 
  9.       } 
  10.       // 返回錯誤信息 
  11.       return ResultVOUtil.error(result.getEnum(ResultEnum.class, "code").getCode(), result.getEnum(ResultEnum.class, "code").getMessage()); 
  12.   }
  •  接口具體實現(xiàn)代碼如下 
 
 
 
 
  1. // 獲取TouchID 
  2.     @Override 
  3.     public JSONObject getTouchID(String userId) { 
  4.         JSONObject returnResult = new JSONObject(); 
  5.         // 根據(jù)當前用戶id從數(shù)據(jù)庫查詢touchId 
  6.         User user = userMapper.getTouchId(userId); 
  7.         String touchId = user.getTouchId(); 
  8.         if (touchId != null) { 
  9.            // touchId存在
  10.             returnResult.put("code", ResultEnum.GET_TOUCHID_SUCCESS); 
  11.             returnResult.put("touchId", touchId); 
  12.             return returnResult; 
  13.         } 
  14.         // touchId不存在
  15.         returnResult.put("code", ResultEnum.GET_TOUCHID_ERR); 
  16.         return returnResult; 
  17.     }

注冊TouchID

這個接口用于接收客戶端指紋設備返回的TouchID與客戶端信息,將獲取到的信息保存到數(shù)據(jù)庫的指定用戶。

  •  controller層代碼如下

    @ApiOperation(value = "注冊TouchID", notes = "保存客戶端返回的touchid等信息")

 
 
 
 
  1. @CrossOrigin() 
  2.   @RequestMapping(value = "/registeredTouchID", method = RequestMethod.POST) 
  3.   public ResultVO registeredTouchID(@ApiParam(name = "傳入userId", required = true) @Valid @RequestBody SetTouchIdDto touchIdDto, @RequestHeader(value = "token") String token) {
  4.       JSONObject result = userService.registeredTouchID(touchIdDto.getTouchId(), touchIdDto.getClientDataJson(), JwtUtil.getUserId(token));
  5.       if (result.getEnum(ResultEnum.class, "code").getCode() == 0) { 
  6.           // touchId獲取成功 
  7.           return ResultVOUtil.success(result.getString("data")); 
  8.       } 
  9.       // 返回錯誤信息 
  10.       return ResultVOUtil.error(result.getEnum(ResultEnum.class, "code").getCode(), result.getEnum(ResultEnum.class, "code").getMessage());
  11.    }
  •  接口具體實現(xiàn)代碼如下
 
 
 
 
  1. // 注冊TouchID 
  2.   @Override 
  3.   public JSONObject registeredTouchID(String touchId, String clientDataJson, String userId) { 
  4.       JSONObject result = new JSONObject(); 
  5.       User row = new User(); 
  6.       row.setTouchId(touchId); 
  7.       row.setClientDataJson(clientDataJson); 
  8.       row.setUserId(userId); 
  9.      // 根據(jù)userId更新touchId與客戶端信息 
  10.       int updateResult = userMapper.updateTouchId(row); 
  11.       if (updateResult>0) { 
  12.           result.put("code", ResultEnum.SET_TOUCHED_SUCCESS); 
  13.           result.put("data", "touch_id設置成功"); 
  14.           return result; 
  15.       }
  16.       result.put("code", ResultEnum.SET_TOUCHED_ERR); 
  17.       return result; 
  18.   }

指紋登錄

這個接口接收客戶端發(fā)送的用戶憑證與touchId,隨后將其和數(shù)據(jù)庫中的數(shù)據(jù)進行校驗,返回用戶信息。

  •  controller層代碼如下
 
 
 
 
  1. @ApiOperation(value = "指紋登錄", notes = "通過touchId與用戶憑證登錄系統(tǒng)") 
  2.  @CrossOrigin() 
  3.  @RequestMapping(value = "/touchIdLogin", method = RequestMethod.POST) 
  4.  public ResultVO touchIdLogin(@ApiParam(name = "傳入Touch ID與用戶憑證", required = true) @Valid @RequestBody TouchIDLoginDto touchIDLogin) { 
  5.      JSONObject result = userService.touchIdLogin(touchIDLogin.getTouchId(), touchIDLogin.getCertificate()); 
  6.      return LoginUtil.getLoginResult(result);
  7.  }
  •  接口具體實現(xiàn)代碼如下
 
 
 
 
  1. // 指紋登錄 
  2. @Override 
  3. public JSONObject touchIdLogin(String touchId, String certificate) {
  4.     JSONObject returnResult = new JSONObject(); 
  5.     User row = new User(); 
  6.     row.setTouchId(touchId); 
  7.     row.setUuid(certificate); 
  8.     User user = userMapper.selectUserForTouchId(row);
  9.     String useruserName = user.getUserName(); 
  10.     String useruserId = user.getUserId(); 
  11.     // 用戶名為null則返回錯誤信息 
  12.     if (userName == null) {
  13.         // 指紋認證失敗 
  14.         returnResult.put("code", ResultEnum.TOUCHID_LOGIN_ERR); 
  15.         return returnResult; 
  16.     } 
  17.    // 指紋認證成功,返回用戶信息至客戶端 
  18.    // ... 此處代碼省略,根據(jù)自己的需要返回用戶信息即可 ...// 
  19.    returnResult.put("code", ResultEnum.LOGIN_SUCCESS); 
  20.    return returnResult; 
  21. }

前端實現(xiàn)

前端部分,需要將現(xiàn)有的登錄邏輯和指紋認證相結(jié)合,我們需要實現(xiàn)兩個函數(shù):指紋注冊、指紋登錄。

指紋注冊

這個函數(shù)我們需要接收3個參數(shù):用戶名、用戶id、用戶憑證,我們需要這三個參數(shù)來調(diào)用指紋設備來生成指紋,具體的實現(xiàn)代碼如下:

 
 
 
 
  1. touchIDRegistered: async function( 
  2.   userName: string, 
  3.   userId: string, 
  4.   certificate: string 
  5. ) { 
  6.   // 校驗設備是否支持touchID 
  7.   const hasTouchID = await PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable(); 
  8.   if ( 
  9.     hasTouchID && 
  10.     window.confirm("檢測到您的設備支持指紋登錄,是否啟用?") 
  11.   ) { 
  12.     // 更新注冊憑證 
  13.     thisthis.touchIDOptions.publicKey.challenge = this.base64ToArrayBuffer( 
  14.       certificate 
  15.     );
  16.     // 更新用戶名、用戶id 
  17.     this.touchIDOptions.publicKey.user.name = userName; 
  18.     this.touchIDOptions.publicKey.user.displayName = userName; 
  19.     thisthis.touchIDOptions.publicKey.user.id = this.base64ToArrayBuffer( 
  20.       userId 
  21.     ); 
  22.     // 調(diào)用指紋設備,創(chuàng)建指紋 
  23.     const publicKeyCredential = await navigator.credentials.create(
  24.       this.touchIDOptions 
  25.     ); 
  26.     if (publicKeyCredential && "rawId" in publicKeyCredential) { 
  27.       // 將rowId轉(zhuǎn)為base64 
  28.       const rawId = publicKeyCredential["rawId"]; 
  29.       const touchId = this.arrayBufferToBase64(rawId); 
  30.       const response = publicKeyCredential["response"]; 
  31.       // 獲取客戶端信息 
  32.       const clientDataJSON = this.arrayBufferToString( 
  33.         response["clientDataJSON"] 
  34.       ); 
  35.       // 調(diào)用注冊TouchID接口 
  36.       this.$api.touchIdLogingAPI 
  37.         .registeredTouchID({ 
  38.           touchId: touchId, 
  39.           clientDataJson: clientDataJSON 
  40.         }) 
  41.         .then((res: responseDataType) => { 
  42.           if (res.code === 0) { 
  43.             // 保存touchId用于指紋登錄 
  44.             localStorage.setItem("touchId", touchId); 
  45.             return; 
  46.           } 
  47.           alert(res.msg); 
  48.         }); 
  49.     } 
  50.   } 
  51. }

上面函數(shù)中在創(chuàng)建指紋時,用到了一個對象,它是創(chuàng)建指紋必須要傳的,它的定義以及每個參數(shù)的解釋如下所示:

 
 
 
 
  1. const touchIDOptions = { 
  2.   publicKey: { 
  3.     rp: { name: "chat-system" }, // 網(wǎng)站信息 
  4.     user: { 
  5.       name: "", // 用戶名 
  6.       id: "", // 用戶id(ArrayBuffer) 
  7.       displayName: "" // 用戶名 
  8.     }, 
  9.     pubKeyCredParams: [ 
  10.       { 
  11.         type: "public-key", 
  12.         alg: -7 // 接受的算法 
  13.       } 
  14.     ], 
  15.     challenge: "", // 憑證(touchIDOptions) 
  16.     authenticatorSelection: { 
  17.       authenticatorAttachment: "platform" 
  18.     } 
  19.   } 
  20. }

由于touchIDOptions中,有的參數(shù)需要ArrayBuffer類型,我們數(shù)據(jù)庫保存的數(shù)據(jù)是base64格式的,因此我們需要實現(xiàn)base64與ArrayBuffer之間相互轉(zhuǎn)換的函數(shù),實現(xiàn)代碼如下:

 
 
 
 
  1. base64ToArrayBuffer: function(base64: string) { 
  2.      const binaryString = window.atob(base64); 
  3.      const len = binaryString.length;
  4.      const bytes = new Uint8Array(len); 
  5.      for (let i = 0; i < len; i++) { 
  6.        bytes[i] = binaryString.charCodeAt(i); 
  7.      } 
  8.      return bytes.buffer; 
  9.    }, 
  10.    arrayBufferToBase64: function(buffer: ArrayBuffer) { 
  11.      let binary = ""; 
  12.      const bytes = new Uint8Array(buffer); 
  13.      const len = bytes.byteLength; 
  14.      for (let i = 0; i < len; i++) { 
  15.        binary += String.fromCharCode(bytes[i]); 
  16.      } 
  17.      return window.btoa(binary); 
  18.    }

指紋認證通過后,會在回調(diào)函數(shù)中返回客戶端信息,數(shù)據(jù)類型是ArrayBuffer,數(shù)據(jù)庫需要的格式是string類型,因此我們需要實現(xiàn)ArrayBuffer轉(zhuǎn)string的函數(shù),實現(xiàn)代碼如下:

 
 
 
 
  1. arrayBufferToString: function(buffer: ArrayBuffer) { 
  2.    let binary = ""; 
  3.    const bytes = new Uint8Array(buffer); 
  4.    const len = bytes.byteLength; 
  5.    for (let i = 0; i < len; i++) { 
  6.      binary += String.fromCharCode(bytes[i]); 
  7.    } 
  8.    return binary; 
  9.  }

注意?:用戶憑證中不能包含 _ 和 **-**這兩個字符,否則base64ToArrayBuffer函數(shù)將無法成功轉(zhuǎn)換。

指紋登錄

這個函數(shù)接收2個參數(shù):用戶憑證、設備id,我們會通過這兩個參數(shù)來調(diào)起客戶端的指紋設備來驗證身份,具體的實現(xiàn)代碼如下:

 
 
 
 
  1. touchIDLogin: async function(certificate: string, touchId: string) { 
  2.       // 校驗設備是否支持touchID 
  3.       const hasTouchID = await PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable(); 
  4.       if (hasTouchID) { 
  5.         // 更新登錄憑證 
  6.         thisthis.touchIDLoginOptions.publicKey.challenge = this.base64ToArrayBuffer( 
  7.           certificate 
  8.         ); 
  9.         // 更新touchID 
  10.         this.touchIDLoginOptions.publicKey.allowCredentials[0].id = this.base64ToArrayBuffer( 
  11.           touchId 
  12.         ); 
  13.         // 開始校驗指紋 
  14.         await navigator.credentials.get(this.touchIDLoginOptions);
  15.         // 調(diào)用指紋登錄接口 
  16.         this.$api.touchIdLogingAPI 
  17.           .touchIdLogin({ 
  18.             touchId: touchId, 
  19.             certificate: certificate 
  20.           }) 
  21.           .then((res: responseDataType) => { 
  22.             if (res.code == 0) { 
  23.               // 存儲當前用戶信息 
  24.               localStorage.setItem("token", res.data.token); 
  25.               localStorage.setItem("refreshToken", res.data.refreshToken); 
  26.               localStorage.setItem("profilePicture", res.data.avatarSrc); 
  27.               localStorage.setItem("userID", res.data.userID); 
  28.               localStorage.setItem("username", res.data.username); 
  29.               const certificate = res.data.certificate; 
  30.               localStorage.setItem("certificate", certificate); 
  31.               // 跳轉(zhuǎn)消息組件 
  32.               this.$router.push({ 
  33.                 name: "message" 
  34.               }); 
  35.               return; 
  36.             } 
  37.             // 切回登錄界面
  38.             this.isLoginStatus = loginStatusEnum.NOT_LOGGED_IN; 
  39.             alert(res.msg); 
  40.           }); 
  41.       } 
  42.     }

注意?:注冊新的指紋后,舊的Touch id就會失效,只能通過新的Touch ID來登錄,否則系統(tǒng)無法調(diào)起指紋設備,會報錯:認證出了點問題。

整合現(xiàn)有登錄邏輯

完成上述步驟后,我們已經(jīng)實現(xiàn)了整個指紋的注冊、登錄的邏輯,接下來我們來看看如何將其與現(xiàn)有登錄進行整合。

調(diào)用指紋注冊

當用戶使用用戶名、密碼或者第三方平臺授權登錄成功后,我們就調(diào)用指紋注冊函數(shù),提示用戶是否對本網(wǎng)站進行授權,實現(xiàn)代碼如下:

 
 
 
 
  1. authLogin: function(state: string, code: string, platform: string) { 
  2.      this.$api.authLoginAPI 
  3.        .authorizeLogin({ 
  4.          state: state, 
  5.          code: code, 
  6.          platform: platform 
  7.        }) 
  8.        .then(async (res: responseDataType) => { 
  9.          if (res.code == 0) { 
  10.            //  ... 授權登錄成功,其他代碼省略 ... // 
  11.            // 保存用戶憑證,用于指紋登錄 
  12.            const certificate = res.data.certificate; 
  13.            localStorage.setItem("certificate", certificate); 
  14.            // 校驗設備是否支持touchID 
  15.            const hasTouchID = await PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable(); 
  16.            if (hasTouchID) { 
  17.              //  ... 其他代碼省略 ... // 
  18.              // 獲取Touch ID,檢測用戶是否已授權本網(wǎng)站指紋登錄 
  19.              this.$api.touchIdLogingAPI 
  20.                .getTouchID({ 
  21.                  userId: userId 
  22.                }) 
  23.                .then(async (res: responseDataType) => { 
  24.                  if (res.code !== 0) { 
  25.                    // touchId不存在, 詢問用戶是否注冊touchId 
  26.                    await this.touchIDRegistered(username, userId, certificate); 
  27.                  } 
  28.                  // 保存touchid 
  29.                  localStorage.setItem("touchId", res.data); 
  30.                  // 跳轉(zhuǎn)消息組件 
  31.                  await this.$router.push({ 
  32.                    name: "message" 
  33.                  }); 
  34.                }); 
  35.              return; 
  36.            } 
  37.            // 設備不支持touchID,直接跳轉(zhuǎn)消息組件 
  38.            await this.$router.push({ 
  39.              name: "message" 
  40.            }); 
  41.            return; 
  42.          }
  43.           // 登錄失敗,切回登錄界面 
  44.          this.isLoginStatus = loginStatusEnum.NOT_LOGGED_IN; 
  45.          alert(res.msg); 
  46.        }); 
  47.    }

最終的效果如下所示:

每次第三方平臺授權登錄時都會檢測當前用戶是否已授權本網(wǎng)站,如果已授權則將Touch ID保存至本地,用于通過指紋直接登錄。

調(diào)用指紋登錄

當?shù)卿涰撁婕虞d完畢1s后,我們從用戶本地取出用戶憑證與Touch ID,如果存在則提示用戶是否需要通過指紋來登錄系統(tǒng),具體代碼如下所示:

 
 
 
 
  1. mounted() { 
  2.     const touchId = localStorage.getItem("touchId"); 
  3.     const certificate = localStorage.getItem("certificate"); 
  4.     // 如果touchId存在,則調(diào)用指紋登錄 
  5.     if (touchId && certificate) { 
  6.       // 提示用戶是否需要touchId登錄 
  7.       setTimeout(() => { 
  8.         if (window.confirm("您已授權本網(wǎng)站通過指紋登錄,是否立即登錄?")) { 
  9.           this.touchIDLogin(certificate, touchId); 
  10.         } 
  11.       }, 1000); 
  12.     } 
  13.   }

最終效果如下所示:

項目地址

本文代碼的完整地址請移步:Login.vue

  •  在線體驗地址:chat-system
  •  項目GitHub地址:chat-system-github

文章題目:如何實現(xiàn)Web端指紋登錄
本文URL:http://m.5511xx.com/article/cdhpsde.html