Ultimate Guide to Auth0 In a Chrome Extension Popup

So after reading through the posts here, I was finally able to make things work and want to pay it forward by laying out what I did.

Special thanks to @jannik as I use a lot of his code and ideas here. Also thanks to @dhruv2204 for guiding me in implementing Auth0 inside a background page.

I’m building a Popup Chrome Extension using React and use Auth0 for authentication/authorization.

Whilst I’m using react, I imagine the logic should work if you’re using something else. I’m not using any chrome-extension boilerplate and just use good old npx create-react-app.

It is also worth noting that I already have an existing webapp.

I used the auth0-react library. Initially, I was encountering problems wherein loginWithPopup would close my popup(extension) immediately after authorization. When I would reopen I would reopen the popup I’m already logged out so I really couldn’t login. The only thing that prevented this behavior was if the chrome devtools was open. (setting cacheLocation={'localStorage'} did not fix this which was @jannik’s fix)

What I was finally able to do was:

Have my Sign In button just open up my webapp by calling
chrome.tabs.create({url: 'https://mywebapp.com/'})
Users can then just login there then reopen my popup extension afterwards.

Inside App.js I have this running to check authentication everytime someone opens the popup:

const getToken = async () => {
    try {
      const token = await getAccessTokenSilently()
     setToken(token)
    } catch (e) {
      console.log(e)
    }
  }

  useEffect(() => {
    getToken()
  }, [])

My logic for switching the ui for authenticated user is like this

const { isAuthenticated, getAccessTokenSilently, isLoading } = useAuth0()

const [authenticated, setAuthenticated] = useState(isAuthenticated)

useEffect(()=> {
    setAuthenticated(isAthenticated)
}, [isAuthenticated] )

return(
    <div>
        { isLoading ? <LoadingPage /> : !authenticated ? <SignInPage /> : <HomePage /> }
    </div>
)

The reason why we need to cast isAuthenticated from Auth0 to a custom authenticated state is because we need to manually setAuthenticated(false) on logout. @jannik explains the situation better here Sync auth state between multiple applications (SPA & Chrome Extension) - #21 by jannik

Finally, to Logout, this is what I do. This is basically straight from @jannik

const logoutHandler = () => {
    logoutHelper({ federated: true, returnTo: window.location.origin })
    fetch(`https://${auth0Domain}/v2/logout?federated=true&client_id=${auth0ClientId}`, {
      credentials: 'include',
      mode: 'no-cors'
    }).catch()
  }

  const logoutHelper = (options) => {
    logout(options)
    setAuthenticated(false)
  }

//some button in ui calls logoutHandler() onClick

Hope this helps. If you have suggestions please list it out here and just let me know. Thanks guys!

6 Likes