自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

實(shí)現(xiàn)Web端指紋登錄

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

[[385359]]

本文轉(zhuǎn)載自微信公眾號「神奇的程序員k」,作者神奇的程序員k。轉(zhuǎn)載本文請聯(lián)系神奇的程序員K公眾號。  

前言

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

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

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

實(shí)現(xiàn)思路

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

最終的實(shí)現(xiàn)效果視頻如下所示:

web端指紋登錄的實(shí)現(xiàn)

注冊指紋

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

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

用戶使用其他方式在網(wǎng)站登錄成功后,服務(wù)端返回用戶憑證,將用戶憑證保存到本地

檢測客戶端是否存在指紋設(shè)備

如果存在,將服務(wù)端返回的用戶憑證與用戶信息傳遞給指紋注冊函數(shù)來創(chuàng)建指紋

身份認(rèn)證成功,回調(diào)函數(shù)返回設(shè)備id與客戶端信息,將設(shè)備id保存到本地

將設(shè)備id與客戶端信息發(fā)送至服務(wù)端,將其存儲到指定用戶數(shù)據(jù)中。

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

指紋認(rèn)證

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

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

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

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

實(shí)現(xiàn)過程

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

服務(wù)端實(shí)現(xiàn)

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

獲取TouchID

這個(gè)接口用于判斷登錄用戶是否已經(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.         // 返回錯(cuò)誤信息 
  11.         return ResultVOUtil.error(result.getEnum(ResultEnum.class, "code").getCode(), result.getEnum(ResultEnum.class, "code").getMessage()); 
  12.     } 
  • 接口具體實(shí)現(xiàn)代碼如下
  1. // 獲取TouchID 
  2.     @Override 
  3.     public JSONObject getTouchID(String userId) { 
  4.         JSONObject returnResult = new JSONObject(); 
  5.         // 根據(jù)當(dāng)前用戶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

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

  • controller層代碼如下
  1. @ApiOperation(value = "注冊TouchID", notes = "保存客戶端返回的touchid等信息"
  2.     @CrossOrigin() 
  3.     @RequestMapping(value = "/registeredTouchID", method = RequestMethod.POST) 
  4.     public ResultVO<?> registeredTouchID(@ApiParam(name = "傳入userId", required = true) @Valid @RequestBody SetTouchIdDto touchIdDto, @RequestHeader(value = "token") String token) { 
  5.         JSONObject result = userService.registeredTouchID(touchIdDto.getTouchId(), touchIdDto.getClientDataJson(), JwtUtil.getUserId(token)); 
  6.         if (result.getEnum(ResultEnum.class, "code").getCode() == 0) { 
  7.             // touchId獲取成功 
  8.             return ResultVOUtil.success(result.getString("data")); 
  9.         } 
  10.         // 返回錯(cuò)誤信息 
  11.         return ResultVOUtil.error(result.getEnum(ResultEnum.class, "code").getCode(), result.getEnum(ResultEnum.class, "code").getMessage()); 
  12.     } 
  • 接口具體實(shí)現(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設(shè)置成功"); 
  14.             return result; 
  15.         } 
  16.         result.put("code", ResultEnum.SET_TOUCHED_ERR); 
  17.         return result; 
  18.     } 

指紋登錄

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

  • 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.     } 
  • 接口具體實(shí)現(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 userName = user.getUserName(); 
  10.         String userId = user.getUserId(); 
  11.         // 用戶名為null則返回錯(cuò)誤信息 
  12.         if (userName == null) { 
  13.             // 指紋認(rèn)證失敗 
  14.             returnResult.put("code", ResultEnum.TOUCHID_LOGIN_ERR); 
  15.             return returnResult; 
  16.         } 
  17.        // 指紋認(rèn)證成功,返回用戶信息至客戶端 
  18.        // ... 此處代碼省略,根據(jù)自己的需要返回用戶信息即可 ...// 
  19.        returnResult.put("code", ResultEnum.LOGIN_SUCCESS); 
  20.        return returnResult; 
  21.     } 

前端實(shí)現(xiàn)

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

指紋注冊

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

  1. touchIDRegistered: async function
  2.       userName: string, 
  3.       userId: string, 
  4.       certificate: string 
  5.     ) { 
  6.       // 校驗(yàn)設(shè)備是否支持touchID 
  7.       const hasTouchID = await PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable(); 
  8.       if ( 
  9.         hasTouchID && 
  10.         window.confirm("檢測到您的設(shè)備支持指紋登錄,是否啟用?"
  11.       ) { 
  12.         // 更新注冊憑證 
  13.         this.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.         this.touchIDOptions.publicKey.user.id = this.base64ToArrayBuffer( 
  20.           userId 
  21.         ); 
  22.         // 調(diào)用指紋設(shè)備,創(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<string>) => { 
  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)建指紋時(shí),用到了一個(gè)對象,它是創(chuàng)建指紋必須要傳的,它的定義以及每個(gè)參數(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.   } 

由于touchIDOptions中,有的參數(shù)需要ArrayBuffer類型,我們數(shù)據(jù)庫保存的數(shù)據(jù)是base64格式的,因此我們需要實(shí)現(xiàn)base64與ArrayBuffer之間相互轉(zhuǎn)換的函數(shù),實(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.     } 

指紋認(rèn)證通過后,會在回調(diào)函數(shù)中返回客戶端信息,數(shù)據(jù)類型是ArrayBuffer,數(shù)據(jù)庫需要的格式是string類型,因此我們需要實(shí)現(xiàn)ArrayBuffer轉(zhuǎn)string的函數(shù),實(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.     } 

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

指紋登錄

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

  1. touchIDLogin: async function(certificate: string, touchId: string) { 
  2.       // 校驗(yàn)設(shè)備是否支持touchID 
  3.       const hasTouchID = await PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable(); 
  4.       if (hasTouchID) { 
  5.         // 更新登錄憑證 
  6.         this.touchIDLoginOptions.publicKey.challenge = this.base64ToArrayBuffer( 
  7.           certificate 
  8.         ); 
  9.         // 更新touchID 
  10.         this.touchIDLoginOptions.publicKey.allowCredentials[0].id = this.base64ToArrayBuffer( 
  11.           touchId 
  12.         ); 
  13.         // 開始校驗(yàn)指紋 
  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.               // 存儲當(dāng)前用戶信息 
  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)起指紋設(shè)備,會報(bào)錯(cuò):認(rèn)證出了點(diǎn)問題。

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

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

調(diào)用指紋注冊

當(dāng)用戶使用用戶名、密碼或者第三方平臺授權(quán)登錄成功后,我們就調(diào)用指紋注冊函數(shù),提示用戶是否對本網(wǎng)站進(jìn)行授權(quán),實(shí)現(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.            //  ... 授權(quán)登錄成功,其他代碼省略 ... // 
  11.            // 保存用戶憑證,用于指紋登錄 
  12.            const certificate = res.data.certificate; 
  13.            localStorage.setItem("certificate", certificate); 
  14.            // 校驗(yàn)設(shè)備是否支持touchID 
  15.            const hasTouchID = await PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable(); 
  16.            if (hasTouchID) { 
  17.              //  ... 其他代碼省略 ... // 
  18.              // 獲取Touch ID,檢測用戶是否已授權(quán)本網(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.            // 設(shè)備不支持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.    } 

最終的效果如下所示:

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

調(diào)用指紋登錄

當(dāng)?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("您已授權(quán)本網(wǎng)站通過指紋登錄,是否立即登錄?")) { 
  9.           this.touchIDLogin(certificate, touchId); 
  10.         } 
  11.       }, 1000); 
  12.     } 
  13.   } 

最終效果如下所示:

項(xiàng)目地址

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

  • 在線體驗(yàn)地址:chat-system
  • 項(xiàng)目GitHub地址:chat-system-github

 

責(zé)任編輯:武曉燕 來源: 神奇的程序員k
相關(guān)推薦

2021-08-20 09:50:41

Web指紋前端

2020-07-30 09:34:10

安全信息安全Web

2021-11-06 07:42:04

驗(yàn)證開發(fā)流程

2021-04-27 07:00:08

UbuntuLinux指紋登錄

2009-06-18 10:11:59

指紋Web安全

2019-11-23 15:45:38

Web指紋識別指紋

2021-02-11 13:56:21

JSweb插件

2011-04-07 09:33:01

Activex

2023-11-23 14:37:29

2020-08-16 08:51:22

WEB安全網(wǎng)絡(luò)攻擊網(wǎng)絡(luò)欺騙

2015-08-28 09:40:39

自動登錄webapp

2012-01-18 10:20:31

2022-09-02 10:20:44

網(wǎng)絡(luò)切片網(wǎng)絡(luò)5G

2019-09-25 17:12:44

2018-12-25 23:01:14

2017-06-28 09:11:13

聯(lián)想企業(yè)網(wǎng)盤

2013-06-08 09:59:15

VMwarevSphere Web

2020-08-03 15:40:57

Web自動化工具測試

2020-06-09 15:13:15

2012-08-24 09:34:58

戴爾
點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號