App to Web: auto-login flow

App to Web: auto-login flow

ยท

4 min read

This week I was working on the auto-login mechanism, which has a very significant role in the smoothening user journey and good user experience from native apps to the web.

Problem

Use-case is pretty simple, a user is logged in to a native app (mobile or desktop) and needs to perform some authenticated operation on the web to complete its journey. The native app should open the default browser (either chrome or safari) and ensure the user is already logged into the browser with the same account he/she has in the native app.

The auto-login should be:

  • Automated: no manual clicks/operations required
  • Secure: encrypted over HTTPS
  • Not replicable: the URL redirected to web from native app should work at most once

Prerequisites

The user is logged in to the native app (mobile or desktop) and has an access token.

The Solution

  1. The native app calls an authenticated API and get a secure, short-lived, one-time single sign-on(SSO) token.
  2. The native app embeds the SSO token and a redirection URL in the base URL and opens the browser at the base URL.
  3. The web application checks the SSO token validity (not expired, not already used), logins the user with the same account that generated the token, and redirects the user to the redirection URL.

Implementation ( Optional)

My use case was for a web application that is server-side rendered using Nuxt.js and Vue.

  • Create a new authenticated endpoint that will generate and return an SSO token for the individual user. Token will be valid for only a single-use and will be flagged invalid/overridden after use. weeklydevapi.hashnode.dev/user/one-time-token ( Get API)

  • Perform the get call from the native app and generate a URL and perform redirection. weeklydevapi.hashnode.dev/auto-login?token=${ssoToken}&redirectionUrl=${redirectionUrl}

  • A new URL in your web application /auto-login to handle the authentication operation and redirect to the redirection URL after authentication.

  • Create a new endpoint to log in to the user using the SSO token on the web application, it will return the auth-token in response headers. weeklydevapi.hashnode.dev/user/one-time-token/verify (Post Api)

  • Since in my implementation, the auto-login page is server-side rendered and nuxt.js provides the flexibility of setting cookies on the server-side. So you can use the nuxt.js asyncData hook and call the post API with SSO token and then set the auth-token from the response headers in the cookies (on the server-side).

  • Then you can use the redirect method attached to the context of asyncData hook and redirect to redirectionUrl on the server-side itself.

  • Finally, you will land on the desired page with the user already logged in to perform any authenticated action on the web.