溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

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

發(fā)布時(shí)間:2021-07-16 10:56:17 來源:億速云 閱讀:243 作者:chen 欄目:安全技術(shù)

這篇文章主要介紹“如何實(shí)現(xiàn)Web端指紋登錄”,在日常操作中,相信很多人在如何實(shí)現(xiàn)Web端指紋登錄問題上存在疑惑,小編查閱了各式資料,整理出簡單好用的操作方法,希望對(duì)大家解答”如何實(shí)現(xiàn)Web端指紋登錄”的疑惑有所幫助!接下來,請(qǐng)跟著小編一起來學(xué)習(xí)吧!

前言

現(xiàn)在越來越多的筆記本電腦內(nèi)置了指紋識(shí)別,用于快速從鎖屏進(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ù)會(huì)返回設(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ù)端,將其存儲(chǔ)到指定用戶數(shù)據(jù)中。

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

指紋認(rèn)證

用戶在我們網(wǎng)站授權(quán)指紋登錄后,會(huì)將用戶憑證與設(shè)備id保存在本地,當(dāng)用戶進(jìn)入我們網(wǎng)站時(shí),會(huì)從本地拿到這兩條數(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層代碼如下

@ApiOperation(value = "獲取TouchID", notes = "通過用戶id獲取指紋登錄所需憑據(jù)")     @CrossOrigin()     @RequestMapping(value = "/getTouchID", method = RequestMethod.POST)     public ResultVO<?> getTouchID(@ApiParam(name = "傳入userId", required = true) @Valid @RequestBody GetTouchIdDto touchIdDto, @RequestHeader(value = "token") String token) {         JSONObject result = userService.getTouchID(JwtUtil.getUserId(token));         if (result.getEnum(ResultEnum.class, "code").getCode() == 0) {             // touchId獲取成功             return ResultVOUtil.success(result.getString("touchId"));         }         // 返回錯(cuò)誤信息         return ResultVOUtil.error(result.getEnum(ResultEnum.class, "code").getCode(), result.getEnum(ResultEnum.class, "code").getMessage());     }
  • 接口具體實(shí)現(xiàn)代碼如下

// 獲取TouchID     @Override     public JSONObject getTouchID(String userId) {         JSONObject returnResult = new JSONObject();         // 根據(jù)當(dāng)前用戶id從數(shù)據(jù)庫查詢touchId         User user = userMapper.getTouchId(userId);         String touchId = user.getTouchId();         if (touchId != null) {            // touchId存在             returnResult.put("code", ResultEnum.GET_TOUCHID_SUCCESS);             returnResult.put("touchId", touchId);             return returnResult;         }         // touchId不存在         returnResult.put("code", ResultEnum.GET_TOUCHID_ERR);         return returnResult;     }

注冊TouchID

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

  • controller層代碼如下

@ApiOperation(value = "注冊TouchID", notes = "保存客戶端返回的touchid等信息")     @CrossOrigin()     @RequestMapping(value = "/registeredTouchID", method = RequestMethod.POST)     public ResultVO<?> registeredTouchID(@ApiParam(name = "傳入userId", required = true) @Valid @RequestBody SetTouchIdDto touchIdDto, @RequestHeader(value = "token") String token) {         JSONObject result = userService.registeredTouchID(touchIdDto.getTouchId(), touchIdDto.getClientDataJson(), JwtUtil.getUserId(token));         if (result.getEnum(ResultEnum.class, "code").getCode() == 0) {             // touchId獲取成功             return ResultVOUtil.success(result.getString("data"));         }         // 返回錯(cuò)誤信息         return ResultVOUtil.error(result.getEnum(ResultEnum.class, "code").getCode(), result.getEnum(ResultEnum.class, "code").getMessage());     }
  • 接口具體實(shí)現(xiàn)代碼如下

// 注冊TouchID     @Override     public JSONObject registeredTouchID(String touchId, String clientDataJson, String userId) {         JSONObject result = new JSONObject();         User row = new User();         row.setTouchId(touchId);         row.setClientDataJson(clientDataJson);         row.setUserId(userId);        // 根據(jù)userId更新touchId與客戶端信息         int updateResult = userMapper.updateTouchId(row);         if (updateResult>0) {             result.put("code", ResultEnum.SET_TOUCHED_SUCCESS);             result.put("data", "touch_id設(shè)置成功");             return result;         }         result.put("code", ResultEnum.SET_TOUCHED_ERR);         return result;     }

指紋登錄

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

  • controller層代碼如下

@ApiOperation(value = "指紋登錄", notes = "通過touchId與用戶憑證登錄系統(tǒng)")     @CrossOrigin()     @RequestMapping(value = "/touchIdLogin", method = RequestMethod.POST)     public ResultVO<?> touchIdLogin(@ApiParam(name = "傳入Touch ID與用戶憑證", required = true) @Valid @RequestBody TouchIDLoginDto touchIDLogin) {         JSONObject result = userService.touchIdLogin(touchIDLogin.getTouchId(), touchIDLogin.getCertificate());         return LoginUtil.getLoginResult(result);     }
  • 接口具體實(shí)現(xiàn)代碼如下

// 指紋登錄     @Override     public JSONObject touchIdLogin(String touchId, String certificate) {         JSONObject returnResult = new JSONObject();         User row = new User();         row.setTouchId(touchId);         row.setUuid(certificate);         User user = userMapper.selectUserForTouchId(row);         String userName = user.getUserName();         String userId = user.getUserId();         // 用戶名為null則返回錯(cuò)誤信息         if (userName == null) {             // 指紋認(rèn)證失敗             returnResult.put("code", ResultEnum.TOUCHID_LOGIN_ERR);             return returnResult;         }        // 指紋認(rèn)證成功,返回用戶信息至客戶端        // ... 此處代碼省略,根據(jù)自己的需要返回用戶信息即可 ...//        returnResult.put("code", ResultEnum.LOGIN_SUCCESS);        return returnResult;     }

前端實(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)代碼如下:

touchIDRegistered: async function(       userName: string,       userId: string,       certificate: string     ) {       // 校驗(yàn)設(shè)備是否支持touchID       const hasTouchID = await PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable();       if (         hasTouchID &&         window.confirm("檢測到您的設(shè)備支持指紋登錄,是否啟用?")       ) {         // 更新注冊憑證         this.touchIDOptions.publicKey.challenge = this.base64ToArrayBuffer(           certificate         );         // 更新用戶名、用戶id         this.touchIDOptions.publicKey.user.name = userName;         this.touchIDOptions.publicKey.user.displayName = userName;         this.touchIDOptions.publicKey.user.id = this.base64ToArrayBuffer(           userId         );         // 調(diào)用指紋設(shè)備,創(chuàng)建指紋         const publicKeyCredential = await navigator.credentials.create(           this.touchIDOptions         );         if (publicKeyCredential && "rawId" in publicKeyCredential) {           // 將rowId轉(zhuǎn)為base64           const rawId = publicKeyCredential["rawId"];           const touchId = this.arrayBufferToBase64(rawId);           const response = publicKeyCredential["response"];           // 獲取客戶端信息           const clientDataJSON = this.arrayBufferToString(             response["clientDataJSON"]           );           // 調(diào)用注冊TouchID接口           this.$api.touchIdLogingAPI             .registeredTouchID({               touchId: touchId,               clientDataJson: clientDataJSON             })             .then((res: responseDataType<string>) => {               if (res.code === 0) {                 // 保存touchId用于指紋登錄                 localStorage.setItem("touchId", touchId);                 return;               }               alert(res.msg);             });         }       }     }

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

const touchIDOptions = {   publicKey: {     rp: { name: "chat-system" }, // 網(wǎng)站信息     user: {       name: "", // 用戶名       id: "", // 用戶id(ArrayBuffer)       displayName: "" // 用戶名     },     pubKeyCredParams: [       {         type: "public-key",         alg: -7 // 接受的算法       }     ],     challenge: "", // 憑證(touchIDOptions)     authenticatorSelection: {       authenticatorAttachment: "platform"     }   } }

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

base64ToArrayBuffer: function(base64: string) {       const binaryString = window.atob(base64);       const len = binaryString.length;       const bytes = new Uint8Array(len);       for (let i = 0; i < len; i++) {         bytes[i] = binaryString.charCodeAt(i);       }       return bytes.buffer;     },     arrayBufferToBase64: function(buffer: ArrayBuffer) {       let binary = "";       const bytes = new Uint8Array(buffer);       const len = bytes.byteLength;       for (let i = 0; i < len; i++) {         binary += String.fromCharCode(bytes[i]);       }       return window.btoa(binary);     }

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

arrayBufferToString: function(buffer: ArrayBuffer) {       let binary = "";       const bytes = new Uint8Array(buffer);       const len = bytes.byteLength;       for (let i = 0; i < len; i++) {         binary += String.fromCharCode(bytes[i]);       }       return binary;     }

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

指紋登錄

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

touchIDLogin: async function(certificate: string, touchId: string) {       // 校驗(yàn)設(shè)備是否支持touchID       const hasTouchID = await PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable();       if (hasTouchID) {         // 更新登錄憑證         this.touchIDLoginOptions.publicKey.challenge = this.base64ToArrayBuffer(           certificate         );         // 更新touchID         this.touchIDLoginOptions.publicKey.allowCredentials[0].id = this.base64ToArrayBuffer(           touchId         );         // 開始校驗(yàn)指紋         await navigator.credentials.get(this.touchIDLoginOptions);         // 調(diào)用指紋登錄接口         this.$api.touchIdLogingAPI           .touchIdLogin({             touchId: touchId,             certificate: certificate           })           .then((res: responseDataType) => {             if (res.code == 0) {               // 存儲(chǔ)當(dāng)前用戶信息               localStorage.setItem("token", res.data.token);               localStorage.setItem("refreshToken", res.data.refreshToken);               localStorage.setItem("profilePicture", res.data.avatarSrc);               localStorage.setItem("userID", res.data.userID);               localStorage.setItem("username", res.data.username);               const certificate = res.data.certificate;               localStorage.setItem("certificate", certificate);               // 跳轉(zhuǎn)消息組件               this.$router.push({                 name: "message"               });               return;             }             // 切回登錄界面             this.isLoginStatus = loginStatusEnum.NOT_LOGGED_IN;             alert(res.msg);           });       }     }

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

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

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

調(diào)用指紋注冊

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

authLogin: function(state: string, code: string, platform: string) {      this.$api.authLoginAPI        .authorizeLogin({          state: state,          code: code,          platform: platform        })        .then(async (res: responseDataType) => {          if (res.code == 0) {            //  ... 授權(quán)登錄成功,其他代碼省略 ... //            // 保存用戶憑證,用于指紋登錄            const certificate = res.data.certificate;            localStorage.setItem("certificate", certificate);            // 校驗(yàn)設(shè)備是否支持touchID            const hasTouchID = await PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable();            if (hasTouchID) {              //  ... 其他代碼省略 ... //              // 獲取Touch ID,檢測用戶是否已授權(quán)本網(wǎng)站指紋登錄              this.$api.touchIdLogingAPI                .getTouchID({                  userId: userId                })                .then(async (res: responseDataType) => {                  if (res.code !== 0) {                    // touchId不存在, 詢問用戶是否注冊touchId                    await this.touchIDRegistered(username, userId, certificate);                  }                  // 保存touchid                  localStorage.setItem("touchId", res.data);                  // 跳轉(zhuǎn)消息組件                  await this.$router.push({                    name: "message"                  });                });              return;            }            // 設(shè)備不支持touchID,直接跳轉(zhuǎn)消息組件            await this.$router.push({              name: "message"            });            return;          }          // 登錄失敗,切回登錄界面          this.isLoginStatus = loginStatusEnum.NOT_LOGGED_IN;          alert(res.msg);        });    }

最終的效果如下所示:

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

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

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

調(diào)用指紋登錄

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

mounted() {     const touchId = localStorage.getItem("touchId");     const certificate = localStorage.getItem("certificate");     // 如果touchId存在,則調(diào)用指紋登錄     if (touchId && certificate) {       // 提示用戶是否需要touchId登錄       setTimeout(() => {         if (window.confirm("您已授權(quán)本網(wǎng)站通過指紋登錄,是否立即登錄?")) {           this.touchIDLogin(certificate, touchId);         }       }, 1000);     }   }

最終效果如下所示:

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

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

項(xiàng)目地址

本文代碼的完整地址請(qǐng)移步:Login.vue

  • 在線體驗(yàn)地址:chat-system

  • 項(xiàng)目GitHub地址:chat-system-github

到此,關(guān)于“如何實(shí)現(xiàn)Web端指紋登錄”的學(xué)習(xí)就結(jié)束了,希望能夠解決大家的疑惑。理論與實(shí)踐的搭配能更好的幫助大家學(xué)習(xí),快去試試吧!若想繼續(xù)學(xué)習(xí)更多相關(guān)知識(shí),請(qǐng)繼續(xù)關(guān)注億速云網(wǎng)站,小編會(huì)繼續(xù)努力為大家?guī)砀鄬?shí)用的文章!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI