WebAuthn(也叫Web Authentication API)是Credential Management API的一个扩展,它经过公钥保证了免密认证的安全性。咱们经过一个Demo来看它作了什么。git
WebAuthn用公钥证书代替了密码,完成用户的注册和身份认证(登陆)。它更像是现有身份认证的加强或补充。为了保证通讯数据安全,通常基于HTTPS(TLS)通讯。在这个过程当中,有4个模块。github
注册过程分为7个阶段web
浏览器发起注册请求,包含用户基本信息。浏览器
这是一个异步任务,JS脚本调用浏览器的navigator.credentials.create建立证书。安全
getMakeCredentialsChallenge({username, name})
.then((response) => {
let publicKey = preformatMakeCredReq(response);
return navigator.credentials.create({ publicKey })
})
.then((response) => {
console.log(response);
let makeCredResponse = publicKeyCredentialToJSON(response);
return sendWebAuthnResponse(makeCredResponse)
})
.then((response) => {
if(response.status === 'ok') {
loadMainContainer()
} else {
alert(`Server responed with error. The message is: ${response.message}`);
}
})
.catch((error) => alert(error))
复制代码
浏览器到认证模块之间的数据用JSON格式传递,并包含如下内容:服务器
浏览器会以{ AttestationObject, ClientDataJSON }的格式返回给JS脚本。异步
检查Challenge、Origin,并存储公钥和用户信息。ui
一样分为7步,多数内容与注册类似。url
浏览器发起登陆请求,包含用户基本信息。spa
JS脚本调用浏览器的navigator.credentials.get检索证书。
getGetAssertionChallenge({username})
.then((response) => {
console.log(response)
let publicKey = preformatGetAssertReq(response);
return navigator.credentials.get({ publicKey })
})
.then((response) => {
console.log(response)
let getAssertionResponse = publicKeyCredentialToJSON(response);
return sendWebAuthnResponse(getAssertionResponse)
})
.then((response) => {
if(response.status === 'ok') {
loadMainContainer()
} else {
alert(`Server responed with error. The message is: ${response.message}`);
}
})
.catch((error) => alert(error))
复制代码
检查Challenge、Origin,并验证公钥和用户信息。
let verifyAuthenticatorAssertionResponse = (webAuthnResponse, authenticators) => {
let authr = findAuthr(webAuthnResponse.id, authenticators);
let authenticatorData = base64url.toBuffer(webAuthnResponse.response.authenticatorData);
let response = {'verified': false};
if(authr.fmt === 'fido-u2f') {
let authrDataStruct = parseGetAssertAuthData(authenticatorData);
if(!(authrDataStruct.flags & U2F_USER_PRESENTED))
throw new Error('User was NOT presented durring authentication!');
let clientDataHash = hash(base64url.toBuffer(webAuthnResponse.response.clientDataJSON))
let signatureBase = Buffer.concat([authrDataStruct.rpIdHash, authrDataStruct.flagsBuf, authrDataStruct.counterBuf, clientDataHash]);
let publicKey = ASN1toPEM(base64url.toBuffer(authr.publicKey));
let signature = base64url.toBuffer(webAuthnResponse.response.signature);
response.verified = verifySignature(signature, signatureBase, publicKey)
if(response.verified) {
if(response.counter <= authr.counter)
throw new Error('Authr counter did not increase!');
authr.counter = authrDataStruct.counter
}
}
return response
}
复制代码