DEV Community

Daniel Bayerlein
Daniel Bayerlein

Posted on

5 3

Custom React Hook for Authentication with Amazon Cognito

In one of my last projects I used Amazon Cognito with Azure AD B2C as identity provider. I wrote the following post about this integration:

For a plug & play integration into a React application I used the @aws-amplify/auth library for authentication.

The integration is very easy, but with a React Hook it is even easier. So I created a simple React Hook that I would like to share with you now, maybe it will help you. It is not bound to Azure, you can use it with any OIDC identity provider.

Let's take a closer look at this one. The hook accepts an object { provider, options } as param. provider is the identity provider name you specified in Amazon Cognito. options are the AWS Amplify auth options, see the API documentation for the complete list.

The hook returns the functions signIn() and signOut() as well as an identifier (isSignedIn) for the login status and last but not least the logged in user (user).

import { useState, useEffect, useMemo } from 'react'
import Auth from '@aws-amplify/auth'

export default ({ provider, options }) => {
  const [state, setState] = useState({
    user: {},
    isSignedIn: false
  })

  const auth = useMemo(() => {
    Auth.configure(options)
    return Auth
  }, [])

  useEffect(() => {
    auth.currentAuthenticatedUser()
      .then((user) => setState({ user, isSignedIn: true }))
      .catch(() => {})
  }, [])

  const signIn = () => auth.federatedSignIn({ provider })

  const signOut = () => auth.signOut()

  return {
    ...state,
    signIn,
    signOut
  }
}
Enter fullscreen mode Exit fullscreen mode

As soon as you call the signIn() function, you will be redirected to the login page of the IdP. Afterwards you are returned to the application, see redirectSignIn option.

If the signOut() function is called, the logout is performed and you are returned to the application, see redirectSignOut option.

Here is an example with the React useAuth() hook in action.

import React from 'react'
import useAuth from '../hooks/useAuth'

const App = () => {
  const { signIn, signOut, user, isSignedIn } = useAuth({
    provider: 'Azure-AD-B2C',
    options: {
      userPoolId: 'eu-central-1_aabbccddeeff',
      userPoolWebClientId: '1a2b3c4d5e6f7g8h9i0',
      oauth: {
        domain: 'cognito-with-azure-example.auth.eu-central-1.amazoncognito.com',
        scope: ['email', 'aws.cognito.signin.user.admin', 'openid'],
        redirectSignIn: 'http://localhost:8080',
        redirectSignOut: 'http://localhost:8080',
        region: 'eu-central-1',
        responseType: 'code'
      }
    }
  })

  return (
    <>
      {isSignedIn ? (
        <div style={{ whiteSpace: 'pre' }}>
          <button onClick={() => signOut()}>Logout</button>
          <h1>Hi {user.username}</h1>
          <code>{JSON.stringify(user, null, 2)}</code>
        </div>
      ) : (
        <button onClick={() => signIn()}>Login</button>
      )}
    </>
  )
}

export default App
Enter fullscreen mode Exit fullscreen mode

You can also use this hook centrally together with the React Context in your application.


If you have any kind of feedback, suggestions or ideas - feel free to comment this post!

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay