Skip to main content

Implementing login and signup on React with Cryptr

Cryptr - React illustration

Beginner React Tutorial with Cryptr Authentication

React v16.13.115min

Learn how to build a React application that includes Cryptr authentication.

In this tutorial, weโ€™ll walk you through the process of building a React application from scratch and secure it by implementing the Cryptr authentication. You'll just need to have a code editor (I personally use VS Code) and access to the terminal in order to complete this tutorial.

Let's get started! ๐Ÿ˜‰

1. Get the Starter Applicationโ€‹

๐Ÿ›  Clone the shark-academy-react-template repository to get started:

git clone https://github.com/cryptr-examples/shark-academy-react-template.git

๐Ÿ›  Once youโ€™ve cloned the repo, go to shark-academy-react-template with command:

cd shark-academy-react-template

๐Ÿ›  Install the React project dependencies with yarn or yarn install

๐Ÿ›  You can run the React application with yarn start

2. Application Keysโ€‹

Create application with Cryptrโ€‹

You will use Cryptrโ€™s authentication service to do the tutorial.

๐Ÿ› ๏ธ๏ธ First, sign up for a free Cryptr account here. Once you're registered, you'll be taken to the Cryptr Onboarding to create your application

Rendering Rendering

๐Ÿ› ๏ธ๏ธ You can then create your application by following the onboarding steps.

Rendering

Once you've completed all the funnel, after the processing steps, you arrive on the homepage of the back-office where you have access to various guides that will help you. They will depend on the choices of technology you have made in the funnel.

Rendering

๐Ÿ› ๏ธ๏ธ You can get your environment configuration by first clicking on ยซ applications ยป in the left menu, then by clicking on the application you will have created. A modal will appear and this is where you may copy/paste your environment variables.

Rendering Rendering

Add your Cryptr credentialsโ€‹

๐Ÿ› ๏ธ๏ธ Add a .env file to your environment with the following command:

touch .env

๐Ÿ› ๏ธ๏ธ Then fill the .env file with the variables you'll have retrieved from the Cryptr back-office. Don't forget to replace YOUR_CLIENT_ID & YOUR_DOMAIN with yours.

.env
REACT_APP_CRYPTR_AUDIENCE=http://localhost:3000
REACT_APP_CRYPTR_CLIENT_ID=YOUR_CLIENT_ID
REACT_APP_CRYPTR_DEFAULT_LOCALE=en
REACT_APP_CRYPTR_DEFAULT_REDIRECT_URI=http://localhost:3000
REACT_APP_CRYPTR_TENANT_DOMAIN=YOUR_DOMAIN
REACT_APP_CRYPTR_TELEMETRY=FALSE
REACT_APP_CRYPTR_REGION=eu

Or you may also go to the Cryptr back-office and copy/paste your environment variables in the modal that is displayed as soon as you select your application:

Rendering

Restart the terminal

Make sure to restart your shell/terminal when you modify the environment file

3. Set up the Cryptr React SDKโ€‹

Installationโ€‹

๐Ÿ› ๏ธ๏ธ First, you need to install our package as a dependency:

yarn add @cryptr/cryptr-react

Configure the CryptrProvider componentโ€‹

๐Ÿ› ๏ธ๏ธ Add your cryptrConfig (with your credentials to React) to src/App.js:

src/App.js
const cryptrConfig = {
audience: process.env.REACT_APP_CRYPTR_AUDIENCE,
client_id: process.env.REACT_APP_CRYPTR_CLIENT_ID,
default_locale: process.env.REACT_APP_CRYPTR_DEFAULT_LOCALE,
default_redirect_uri: process.env.REACT_APP_CRYPTR_DEFAULT_REDIRECT_URI,
telemetry: process.env.REACT_APP_CRYPTR_TELEMETRY,
region: process.env.REACT_APP_CRYPTR_REGION,
tenant_domain: process.env.REACT_APP_CRYPTR_TENANT_DOMAIN
}

๐Ÿ› ๏ธ๏ธ Import CryptrProvider from @cryptr/cryptr-react

src/App.js
import { CryptrProvider } from '@cryptr/cryptr-react'

๐Ÿ› ๏ธ๏ธ Wrap your root component, such as App, with CryptrProvider to integrate Cryptr to your React app and integrate cryptrConfig.

src/App.js
const App = () => {
return (
<CryptrProvider {...cryptrConfig}>
<div className="App">
<Router history={history}>
<Nav />
<Switch>
<Route path="/" exact render={() => <Home />}/>
<Route path="/profile" render={() => <Profile />}/>
</Switch>
</Router>
</div>
</CryptrProvider>
);
}

export default App

The CryptrProvider is there to give Cryptr context to Child components. It will be able to handle the user session and retrieve the userโ€™s info to handle your routing for example.

4. Add user authenticationโ€‹

Signupโ€‹

๐Ÿ›  Open up home page in the src/pages/home.js and import SignUpButton

src/pages/home.js
import { SignUpButton} from '@cryptr/cryptr-react'

๐Ÿ›  Replace button tag with SignUpButton component:

src/pages/home.js
<SignUpButton
text="Signup"
className="cursor-pointer sm:mr-8 md:mr-10 rounded-md shadow flex items-center justify-center px-8 py-3 border border-transparent text-sm leading-6 font-bold shadow-md rounded-md uppercase text-gray-900 bg-yellow-400 hover:bg-yellow-300 focus:outline-none focus:border-yellow-500 focus:shadow-outline-yellow transition duration-150 ease-in-out md:py-3 md:text-base md:px-10"
>
</SignUpButton>

Login and logout buttonsโ€‹

๐Ÿ›  Open up nav component in the src/components/Nav.js and import LogOutButton and SignInButton

src/components/Nav.js
import { LogOutButton, SignInButton } from '@cryptr/cryptr-react'

๐Ÿ›  Replace button tags with SignInButton and LogOutButton components:

src/components/Nav.js
<SignInButton 
type="button"
text="Login"
className="relative inline-flex items-center px-5 py-3 border border-transparent text-base uppercase leading-5 font-bold rounded-md text-yellow-500 shadow-md hover:shadow-xl focus:outline-none transition duration-150 ease-in-out">
</SignInButton>
<LogOutButton
type="button"
text="Logout"
className="relative inline-flex items-center px-5 py-3 border border-transparent text-base uppercase leading-5 font-bold rounded-md text-yellow-500 shadow-md hover:shadow-xl focus:outline-none transition duration-150 ease-in-out">
</LogOutButton>
Session Button Components

We can use these components from the Cryptr library which are used for managing the authentication process

๐Ÿ›  Run the server & try to connect. Your React application redirects you to your sign form page, where you can sign in or sign up with an email.

SANDBOX EMAIL

You can log in with a sandbox email and we send you a magic link which should directly arrive in your personal inbox. Your sandbox email is based on your account's email. The email's structure is as follows: my-user-to-test@sandbox.my-admin-name. For example testemail@sandbox.lucas

4. Secure the Profile pageโ€‹

Protect your routesโ€‹

Now is the time to protect your private pages with a guard. Thanks to this little helper, we will easily take advantage of the React router.

touch src/ProtectedRoute.js

๐Ÿ› ๏ธ๏ธ Open up src/ProtectedRoute.js and copy/paste this code:

src/ProtectedRoute.js
import React from 'react'
import { Route } from "react-router-dom"
import { useCryptr } from '@cryptr/cryptr-react'

const ProtectedRoute = ({ component: Component, ...rest }) => {
const {isAuthenticated, signinWithRedirect} = useCryptr()

return (
<Route {...rest} render={(props) => (
isAuthenticated() === true
? <Component {...props} />
: signinWithRedirect()
)}
/>
)}

export default ProtectedRoute
NOTE

isAuthenticated() is a boolean function. Its value is true when Cryptr has authenticated the user and false when it has not.

Inside the render of the <Router> component, we check whether the user is authenticated. If true, the protected component is displayed, if false, the user is redirected to sign form.

๐Ÿ› ๏ธ๏ธ Now open src/App.js, import ProtectedRoute and replace the Route component of the profile path with <ProtectedRoute path="/profile" component={Profile}/>

src/App.js
import './App.css'
import { Router, Route, Switch } from 'react-router-dom'
import history from './utils/history'
import Nav from './components/Nav'
import Home from './pages/home'
import Profile from './pages/profile'
import { CryptrProvider } from '@cryptr/cryptr-react'
// 1. import ProtectedRoute
import ProtectedRoute from './ProtectedRoute'



const cryptrConfig = {
audience: process.env.REACT_APP_CRYPTR_AUDIENCE,
client_id: process.env.REACT_APP_CRYPTR_CLIENT_ID,
default_locale: process.env.REACT_APP_CRYPTR_DEFAULT_LOCALE,
default_redirect_uri: process.env.REACT_APP_CRYPTR_DEFAULT_REDIRECT_URI,
telemetry: process.env.REACT_APP_CRYPTR_TELEMETRY,
region: process.env.REACT_APP_CRYPTR_REGION,
tenant_domain: process.env.REACT_APP_CRYPTR_TENANT_DOMAIN
}

const App = () => {


return (
<CryptrProvider {...cryptrConfig}>
<div className="App">
<Router history={history}>
<Nav />
<Switch>
<Route path="/" exact render={() => <Home />}/>
{/* 2 Replace Route with ProtectedRoute */}
<ProtectedRoute path="/profile" component={Profile}/>
</Switch>
</Router>
</div>
</CryptrProvider>
);
}

export default App

The implementation is now finished. Restart your application and try to go to the profile page, you will be taken to the login page, which is exactly what should happen.

Retrieve User informationโ€‹

Everything in our authentication is gravitating around your end-user. At some point, you may want to retrieve and display user data such as email, metadata, or other attributes attached to their authentication.

If you want to retrieve user data such as emails for example, you can do it through our hook named useCryptr()

Now, we can update the profile page in src/pages/profile.js

๐Ÿ›  First, import useCryptr from @cryptr/cryptr-react

src/pages/profile.js
import React from 'react'
// 1. import useCryptr
import { useCryptr } from '@cryptr/cryptr-react'

const Profile = () => {
// ...

๐Ÿ›  Next, create the cryptrUser constant for user data

src/pages/profile.js
import React from 'react'
// 1. import useCryptr
import { useCryptr } from '@cryptr/cryptr-react'

const Profile = () => {

// 2. Create cryptrUser for user data
const {user: cryptrUser} = useCryptr()

๐Ÿ›  Then, replace the lorem ipsum of p tag with cryptrUser to display the email.

src/pages/profile.js
import React from 'react'
// 1. import useCryptr
import { useCryptr } from '@cryptr/cryptr-react'

const Profile = () => {

// 2. Create cryptrUser for user data
const {user: cryptrUser} = useCryptr()
return (
<div className="py-36 bg-white">
<div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
<div className="lg:text-center">
<p className="text-3xl leading-8 font-extrabold tracking-tight text-gray-900 sm:text-4xl">
This is a profile page
</p>
<p class="mt-4 max-w-2xl text-xl text-gray-500 lg:mx-auto">
{/* Use cryptrUser to display email */}
{cryptrUser().email}
</p>
</div>
</div>
</div>
)
}

export default Profile

Itโ€™s done! You can now start the application with yarn start

Once youโ€™ve logged in, you can view the profile page.

Congratulations if you made it to the end! I hope this was helpful, and thanks for reading! ๐Ÿ™‚