DEV Community

vibhanshu pandey
vibhanshu pandey

Posted on

Auto sign-in user using saved browser credentials

In this post, I'll show you how you can manually prompt a user to save his credentials in the browser when a user registers, and later use it to automatically sign-in the user.

warning: At the time of writing this post, all the browser does not support the PasswordCredential Web API, you can check the supported browsers and browser versions here.

Manually storing credentials in the browser.

const PC = globalThis.PasswordCredential
export const storeCred = async (creds: {
  id: string
  password: string
}): Promise<Credential | null> => {
  // check if PasswordCredential is supported by this browser.
  if (PC) {
    const cred = new PC(creds)
    return navigator.credentials.store(cred)
  } else {
    return null
  }
}
Enter fullscreen mode Exit fullscreen mode

You should call this function after the user registers, change password, and reset password to save/update the credentials in the browser. The id field represents the unique id that the user uses to sign-in, depending upon your application and your sign-in/sign-up process, it could be an email, phone number, or username.

Auto Sign-in when a user visits your site.

To auto sign-in a user, first, we have to retrieve the stored credentials from the browser, then use the credentials to call the sign-in API on the server to sign-in the user.

...
export const fetchCred = async (): Promise<Credential | null> => {
  // check if PasswordCredential is supported by this browser.
  if (PC) {
    return navigator.credentials.get({
      password: true,
    } as any)
  } else {
    return null
  }
}
Enter fullscreen mode Exit fullscreen mode

Usage

...
const cred = await fetchCred()
console.log(cred) 
// { id: 'savedUserId', password: '**********'}
// call the sign-in api, with cred.
...
Enter fullscreen mode Exit fullscreen mode

Prevent auto sign-in after sign-out

Once the user sign-out's itself, you don't want to auto sign-in him again, causing a lock where the user is unable to sign-out himself. This step is very important, as it allows the user to safely sign-out, sign-in with a different account, and register a new account.

export const preventSilentAccess = async (): Promise<void | null> => {
  // check if PasswordCredential is supported by this browser.
  if (PC) {
    return navigator.credentials.preventSilentAccess()
  } else {
    return null
  }
}
Enter fullscreen mode Exit fullscreen mode

After calling the function on sign-out, when the user tries to sign-in, the browser will prompt the user to allow access to the credential, instead of silently providing credentials to the website.

Alt Text

And that's it. :)

Comment down your questions, and if you would like to see a reference implementation in React.

Top comments (1)

Collapse
 
vibhanshu909 profile image
vibhanshu pandey

Who would like to see a reference implementation in React?