如何添加在网站/应用程序上注册和签署多个安全密钥的功能
您如何请求所有已注册的密钥并只对其中一个进行签名?好吧,您需要两个节点包。U2F 用于服务器端,U2F-API 用于服务器端。
当用户想要将他们的一个密钥注册到你的网站上时;你的后端必须向浏览器发出请求。
服务器幻灯片脚本
const u2f = require('u2f');
const APP_ID = "https://..."; // your website URL, must be https
/**
* Server requesting. You can use Express.js to send the request
*/
const request = () => u2f.request(APP_ID);
/**
* @param {{
* version: String,
* appId: String,
* challenge: String
* }} request The request object from the previous function
* @param response Response from U2F key
*/
const verifyRegistration = (request, response) => {
const result = u2f.checkRegistration(request, response);
if (result.successful) {
/**
* store the result.publicKey and result.keyHandle
* to your user database associated with this user
* because we are going to need it later when the user is
* logging into your website with the same security key.
* I recommend you encrypt the public key and key handle
*/
} else {
// failed
};
};
/**
* When the user wants to login with the security key
* @param {String} userID The user's ID
*/
const sign = (userID) => {
/**
* get the user object from your database using the userID
* and map all of the user keys into an array
*/
return userSecurityKeys.map((key) => u2f.request(APP_ID, key.keyHandle));
}
const verifyAuthentication = (userID, request, response) => {
/**
* Quite similar to checkRegistration
*/
userSecurityKeys.some((key, i, { length }) => {
const res = u2f.checkSignature(request, response, key.publicKey);
if (res.successful) {
// return true to stop the .some from looping to other keys
return true
} else {
if (length - 1 === i) reject({
error: true,
status: 400,
message: res.errorMessage || 'Not a registered security key'
});
};
})
};
客户端脚本
import { ensureSupport, sign, register } from "u2f-api";
const registerKey = () => {
ensureSupport()
.then(() => {
// browser supports U2F
register(requestFromServerScript)
.then(registerResponse => {
// send to server
})
.catch(() => {
// error, user clicked on "cancel"?
})
})
.catch(() => {
// browser does not support U2F (looking at you, internet explorer)
});
};
const signKey = () => {
ensureSupport()
.then(() => {
// browser supports U2F
/**
* signRequestsFromServerScript can be an array of
* requests, refer to server-side script "sign" function
*/
sign(signRequestsFromServerScript)
.then(signResponse => {
// send to server
})
.catch(() => {
// error, user clicked on "cancel"?
})
})
.catch(() => {
// browser does not support U2F (looking at you, internet explorer)
});
};