我在使用JSON对象来触发Javascript中的WebAuthn调用时遇到了问题。在编写的navigator.credentials.create()函数上,它期待一个publicKey对象启动启动过程。
现在,我正在使用JSON.parse将字符串解析为一个对象。解析响应字符串后,我将它传递给webAuthn navigator.credentials.create函数,但我得到的错误是:
WebAuth错误:未处理的拒绝(TypeError):无法在“CredentialsContainer”上执行“创建”:无法转换为字典.
有什么问题吗?我已经将它解析为一个对象,其中删除了所有换行符。我怎样才能让这个对象被重新定位?谢谢!
原始响应字符串正在传递
"\"publicKey: {\\n challenge: new Uint8Array(["testnumbers"]).buffer,\\n // Relying Party:\\n rp: {\\n name: \\\"Test.com\\\",\\n id: \\\"test.com\\\"\\n },\\n // User:\\n user: {\\n id: Uint8Array.from(\\\"test\\\", function (c) { return c.charCodeAt(0) }),\\n name: \\\"test@gmail.com\\\",\\n displayName: \\\"test@gmail.com\\\"\\n },\\n pubKeyCredParams: [\\n {\\n type: \\\"public-key\\\",\\n alg: -7\\n }\\n,{\\n type: \\\"public-key\\\",\\n alg: -257\\n }\\n\\n ],\\n attestation: \\\"none\\\",\\n timeout: 60000,\\n excludeCredentials: [],\\n authenticatorSelection: {\\nuserVerification: \\\"discouraged\\\",\\nauthenticatorAttachment: \\\"cross-platform\\\"\\n}\\n};\\n\\n\""发布于 2021-08-23 15:34:18
tl;dr:看起来像一个复杂的JavaScript对象,它包含了对
Uint8Array()的多个引用。
第一件事是在"testnumbers"周围缺少转义引号。
"\"publicKey: {\\n challenge: new Uint8Array(["testnumbers"]).buffer,\\n一个设置为JavaScript语言模式的IDE立即将其调用出来:

引号需要自己的\\\来匹配字符串中的其他引号。
此外,publicKey的开头被转义了,但没有结束:
"\"publicKey:如果您修复了这两个字符串,那么至少可以JSON.parse()字符串,但它只是一个长字符串:
> JSON.parse(foo)
'publicKey: {\n' +
' challenge: new Uint8Array(["testnumbers"]).buffer,\n' +
' // Relying Party:\n' +
' rp: {\n' +
' name: "Test.com",\n' +
' id: "test.com"\n' +
' },\n' +
' // User:\n' +
' user: {\n' +
' id: Uint8Array.from("test", function (c) { return c.charCodeAt(0) }),\n' +
' name: "test@gmail.com",\n' +
' displayName: "test@gmail.com"\n' +
' },\n' +
' pubKeyCredParams: [\n' +
' {\n' +
' type: "public-key",\n' +
' alg: -7\n' +
' }\n' +
',{\n' +
' type: "public-key",\n' +
' alg: -257\n' +
' }\n' +
'\n' +
' ],\n' +
' attestation: "none",\n' +
' timeout: 60000,\n' +
' excludeCredentials: [],\n' +
' authenticatorSelection: {\n' +
'userVerification: "discouraged",\n' +
'authenticatorAttachment: "cross-platform"\n' +
'}\n' +
'};\n' +
'\n'现在,我要指出一个事实,即字符串包含对Uint8Array()的引用--您是否用引号包装了一个复杂的JavaScript对象,并加上注释,然后通过JSON.stringify()运行它?JSON不能包含这样的值,它仅限于字符串、数字、数组和包含这些值的属性的对象等原语。JSON也不支持评论,这可能会让人感到惊讶!
如果您正在生成这个代码服务器端,打算以JSON的形式将其作为JSON传输到前端,然后在浏览器中执行,那么您已经有了正确的想法,但是您的执行还需要改进。
首先,您需要将您的Uint8Array编码成可以编码为字符串的内容。Base64是一种编码方式--将您的challenge和user.id缓冲区编码为字符串,将这些字符串包含在JSON中,然后将字符串转换回浏览器中的缓冲区(作为练习,我将留给读者很多方法来实现这一点)。
如果这个字符串是通过网络请求发送的,那么我建议尝试以JSON的形式发送这段代码,我的意思是将'Content-Type': 'application/json'设置在对返回您要传输的字符串的请求的响应的标题中。让您所使用的任何服务器框架处理通过网络发送JSON的复杂问题,并忘记任何事情。
https://stackoverflow.com/questions/68894921
复制相似问题