Sign Message
Once the connection is complete, we will get the user's JoyID information, such as address, public key, credential, etc. In this guide, we will continue our previous journey in Connect by signing a challenge after the connection is complete.
You can use @joyid/ckb
SDK to sign a challenge. To sign a challenge with the user's JoyID, we need to do the following steps:
Step 1: Save JoyID info
In the previous guide, we have already connected the user with JoyID, and we have got the user's JoyID information. Now we need to save the user's JoyID information. We can save it in the local storage, or in the state of the React component, or in the Vuex store of the Vue app, etc.
import * as React from 'react'
import { connect } from '@joyid/ckb'
import './style.css'
export default function App() {
const onConnect = async () => {
try {
const authData = await connect()
console.log(`JoyID user info:`, authData)
} catch (error) {
console.log(error)
}
}
return (
<div>
<h1>Hello JoyID!</h1>
<button onClick={onConnect}>Connect JoyID</button>
</div>
)
}
Step 2: Sign a challenge
After the connection is complete, we need to add a button
element and listen to the click
event. When the user clicks the button, we will call the signChallenge
function to sign a challenge
with the user's JoyID.
Note that address
is required in the signChallenge
function. You can only sign the challenge
with the user's JoyID if you know the user's address. The address
is included in JoyID info.
import * as React from 'react'
import { connect, signChallenge } from '@joyid/ckb'
import './style.css'
export default function App() {
const [joyidInfo, setJoyidInfo] = React.useState(null)
const [challenge, setChallenge] = React.useState('Sign this for me')
const onConnect = async () => {
try {
const authData = await connect()
setJoyidInfo(authData)
} catch (error) {
console.log(error)
}
}
const onSign = async () => {
const res = await signChallenge(challenge, joyidInfo.address)
if (res) {
alert('Sign message successfully')
console.log(`Sign message result: ${res}`)
}
}
return (
<div id="app">
<h1>Hello JoyID!</h1>
{joyidInfo ? null : <button onClick={onConnect}>Connect JoyID</button>}
{joyidInfo ? (
<div>
<textarea value={challenge} onChange={e => setChallenge(e.target.value)} />
<button onClick={onSign}>Sign With JoyID</button>
</div>
) : null}
</div>
)
}
To learn more about the signChallenge
function, please check the API Reference.
challenge
vs. message
challenge
is what you as a developer want JoyID to sign.
message
is what JoyID actually signs, which is a combination of challenge
and some other data (such as authenticator data, etc.), and challenge
will be always included in message
.
For more information, you can check out the WebAuthn Spec (opens in a new tab).