Sign In with Security Keys
Follow this guide to sign in users with security keys and the WebAuthn API.
Examples of security keys:
- Windows Hello
- Apple Touch ID
- Apple Face ID
- Yubico security keys
- Android Fingerprint sensors
You can read more about this feature in our blog post
Configuration
Enable the Security Key sign-in method in the Nhost dashboard under Settings -> Sign-In Methods -> Security Keys.
You need to make sure you also set a valid client URL under Settings -> Authentication -> Client URL.
Sign Up
Users must use an email address to sign up with a security key.
Here's an example of how to sign up a user with a security key with our JavaScript SDK:
Example:: Sign up with a security key:
const { error, session } = await nhost.auth.signUp({
email: 'joe@example.com',
securityKey: true
})
// Something unexpected happened, for instance, the user canceled the process
if (error) {
console.log(error)
return
}
// if there is no error and no session, the user needs to verify their email address.
if (!session) {
console.log(
'You need to verify your email address by clicking the link in the email we sent you.'
)
return
}
//Sign-up is complete!
console.log(session.user)
Sign In
Once a user signed up with a security key, and verfied their email if needed, they can use it to sign in.
Example: Sign in with a security key:
const { error, session } = await nhost.auth.signIn({
email: 'joe@example.com',
securityKey: true
})
// Something unexpected happened, for instance, the user canceled the process
if (error) {
console.log(error)
return
}
if (!session) {
// Something unexpected happened
console.log(error)
return
}
// User is signed in
Add a Security Key
Any signed-in user with a verified email can add a security key to their user account. Once a security key is added, the user can use it their email and the security key to sign in.
It's possible to add multiple security keys to a user account.
Example: Add a security key to a user account:
const { key, error } = await nhost.auth.addSecurityKey()
// Something unexpected happened
if (error) {
console.log(error)
return
}
// Successfully added a new security key
console.log(key.id)
A nickname can be associated with each security key to make it easier to manage security keys in the future.
Example: Add a security key with a nickname:
await nhost.auth.addSecurityKey('iPhone')
List or Remove Security Keys
To list and remove security keys, use GraphQL and set permissions on the auth.security_keys
table:
Example: Get all security keys for a user:
query securityKeys($userId: uuid!) {
authUserSecurityKeys(where: { userId: { _eq: $userId } }) {
id
nickname
}
}
Example: Remove a security key:
mutation removeSecurityKey($id: uuid!) {
deleteAuthUserSecurityKey(id: $id) {
id
}
}