WebAuthn最小Javascript代码示例
在此页面(一定要有https,感兴趣的同学可以访问http的此页面观察对比现象)
随手打开Console,粘!
或者
注意:里面相关ID的scateu.me字样要与域名相匹配。
注册:
var randomChallengeBuffer = new Uint8Array(32);
window.crypto.getRandomValues(randomChallengeBuffer);
var base64id = 'MIIBkzCCATigAwIBAjCCAZMwggE4oAMCAQIwggGTMII='
var idBuffer = Uint8Array.from(window.atob(base64id), c=>c.charCodeAt(0))
var publicKey = {
challenge: randomChallengeBuffer,
rp: { id: "scateu.me", name: "scateu.me" },
user: {
id: idBuffer,
name: "alice@example.com",
displayName: "Alice von Wunderland"
},
attestation: 'none',
pubKeyCredParams: [
{ type: 'public-key', alg: -7 }, // ES256
{ type: 'public-key', alg: -257 } // RS256
]
}
navigator.credentials.create({ publicKey })
.then((newCredentialInfo) => {
console.log('SUCCESS', newCredentialInfo)
})
.catch((error) => {
console.log('FAIL', error)
})
认证: 把上一步中的ID粘进来
var ID = "cBTxv-1BhIN-GFSeMLife_F5O5iyfawtwvLCNcMF873EbO-CrRtUZHdZHQCLCHWew-bS7LTzlHS_6mlpkl0Dtw"; // CHANGEME
decode = function(input) {
// Replace non-url compatible chars with base64 standard chars
input = input
.replace(/-/g, '+')
.replace(/_/g, '/');
// Pad out with standard base64 required padding characters
var pad = input.length % 4;
if(pad) {
if(pad === 1) {
throw new Error('InvalidLengthError: Input base64url string is the wrong length to determine padding');
}
input += new Array(5-pad).join('=');
}
return input;
};
var randomChallengeBuffer = new Uint8Array(32);
window.crypto.getRandomValues(randomChallengeBuffer);
console.log(navigator.credentials.get({publicKey: {
allowCredentials: [
{
id: Uint8Array.from(atob(decode(ID)), c => c.charCodeAt(0)),
type: "public-key"
}
],
challenge: randomChallengeBuffer,
rpId: "scateu.me",
timeout: 90000,
userVerification: "discouraged"
}
}))