docs: react sdk guide, update quickstart guide to use @zitadel/react (#7300)
* docs: react sdk * docs * doc * checkbox, screen * update quick start guide for react * rm old react * react * cleanup quickstart guide * Update docs/docs/examples/login/react.md Co-authored-by: Dakshitha Ratnayake <dakshitha@users.noreply.github.com> * Update docs/docs/examples/login/react.md Co-authored-by: Dakshitha Ratnayake <dakshitha@users.noreply.github.com> * Update docs/docs/examples/login/react.md Co-authored-by: Dakshitha Ratnayake <dakshitha@users.noreply.github.com> * Update docs/docs/examples/login/react.md Co-authored-by: Dakshitha Ratnayake <dakshitha@users.noreply.github.com> * Update docs/docs/examples/login/react.md Co-authored-by: Dakshitha Ratnayake <dakshitha@users.noreply.github.com> * Update docs/docs/examples/login/react.md Co-authored-by: Dakshitha Ratnayake <dakshitha@users.noreply.github.com> * Update docs/docs/examples/login/react.md Co-authored-by: Dakshitha Ratnayake <dakshitha@users.noreply.github.com> * react + / vue - * remove welcome from screenshot --------- Co-authored-by: Dakshitha Ratnayake <dakshitha@users.noreply.github.com>
120
docs/docs/examples/login/react.md
Normal file
@ -0,0 +1,120 @@
|
|||||||
|
---
|
||||||
|
title: ZITADEL with React
|
||||||
|
sidebar_label: React
|
||||||
|
---
|
||||||
|
|
||||||
|
This integration guide demonstrates the recommended way to incorporate ZITADEL into your React application.
|
||||||
|
It explains how to enable user login in your application and how to fetch data from the user info endpoint.
|
||||||
|
|
||||||
|
By the end of this guide, your application will have login functionality and will be able to access the current user's profile.
|
||||||
|
|
||||||
|
:::tip
|
||||||
|
This documentation references our [example](https://github.com/zitadel/zitadel-react) on GitHub.
|
||||||
|
It also uses the @zitadel/react package with its default configuration.
|
||||||
|
:::
|
||||||
|
|
||||||
|
## Set up application and obtain keys
|
||||||
|
|
||||||
|
Before we begin developing our application, we need to perform a few configuration steps in the ZITADEL Console.
|
||||||
|
You'll need to provide some information about your app.
|
||||||
|
We recommend creating a new app to start from scratch.
|
||||||
|
Navigate to your project, then add a new application at the top of the page.
|
||||||
|
Select the **User Agent** application type and continue.
|
||||||
|
We recommend that you use [Proof Key for Code Exchange (PKCE)](/apis/openidoauth/grant-types#proof-key-for-code-exchange) for all single page applications.
|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
|
### Redirect URIs
|
||||||
|
|
||||||
|
The redirect URIs field tells ZITADEL where it's allowed to redirect users after authentication. For development, you can set dev mode to `true` to enable insecure HTTP and redirect to a `localhost` URI.
|
||||||
|
The post logout redirect sends your users back to a public route on your application after they have logged out.
|
||||||
|
|
||||||
|
:::tip
|
||||||
|
If you are following along with the [example](https://github.com/zitadel/zitadel-react), set the dev mode switch to `true`.
|
||||||
|
Configure a redirect URIs to \http://localhost:3000/callback and a post redirect URI to \http://localhost:3000/.
|
||||||
|
:::
|
||||||
|
|
||||||
|
Continue and create the application.
|
||||||
|
|
||||||
|
### Copy Client ID
|
||||||
|
|
||||||
|
After successful creation of the app, make sure copy the client ID, as you will need it to configure your React client.
|
||||||
|
|
||||||
|
## Create a project role "admin" and assign it to your user
|
||||||
|
|
||||||
|
Also note the projects resource ID, as you will need it to configure your React client.
|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
|
If you want to read your users roles from user info endpoint, make sure to enable the checkbox in your project.
|
||||||
|
|
||||||
|
## React setup
|
||||||
|
|
||||||
|
Now that you have configured your web application on the ZITADEL side, you can proceed with the integration of your React client.
|
||||||
|
|
||||||
|
### Install React dependencies
|
||||||
|
|
||||||
|
To conveniently connect with ZITADEL, you can install the [@zitadel/react NPM package](https://www.npmjs.com/package/@zitadel/react). Run the following command:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
yarn add @zitadel/react
|
||||||
|
```
|
||||||
|
|
||||||
|
### Create and configure the auth service
|
||||||
|
|
||||||
|
The @zitadel/react package provides a `createZitadelAuth()` function which sets some defaults and initializes the underlying [oidc-client-ts](https://github.com/authts/oidc-client-ts) `UserManager` class.
|
||||||
|
You can overwrite all the defaults with the aguments you pass to `createZitadelAuth()`.
|
||||||
|
|
||||||
|
Export the object returned from `createZitadelAuth()`
|
||||||
|
|
||||||
|
### Initialize user manager
|
||||||
|
|
||||||
|
```ts reference
|
||||||
|
https://github.com/zitadel/zitadel-react/blob/main/src/App.tsx
|
||||||
|
```
|
||||||
|
|
||||||
|
### Add two new components to your application
|
||||||
|
|
||||||
|
First, add the component which prompts the user to login.
|
||||||
|
|
||||||
|
```ts reference
|
||||||
|
https://github.com/zitadel/zitadel-react/blob/main/src/components/Login.tsx
|
||||||
|
```
|
||||||
|
|
||||||
|
Then create the component for the page where the users will be redirected.
|
||||||
|
It loads the user info endpoint once the code flow completes and prints all the information.
|
||||||
|
|
||||||
|
```ts reference
|
||||||
|
https://github.com/zitadel/zitadel-react/blob/main/src/components/Callback.tsx
|
||||||
|
```
|
||||||
|
|
||||||
|
You can now read a user's role to show protected areas of the application.
|
||||||
|
|
||||||
|
### Run
|
||||||
|
|
||||||
|
Finally, you can start your application by running the following:
|
||||||
|
|
||||||
|
```
|
||||||
|
yarn start
|
||||||
|
```
|
||||||
|
|
||||||
|
## Completion
|
||||||
|
|
||||||
|
Congratulations! You have successfully integrated your React application with ZITADEL!
|
||||||
|
|
||||||
|
If you get stuck, consider checking out the [ZITADEL React example application](https://github.com/zitadel/zitadel-react).
|
||||||
|
This application includes all the functionalities mentioned in this quickstart.
|
||||||
|
You can start by cloning the repository and changing the arguments to `createZitadelAuth` to fit your requirements.
|
||||||
|
If you face issues, contact us or [raise an issue on GitHub](https://github.com/zitadel/zitadel-react/issues).
|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
|
### What's next?
|
||||||
|
|
||||||
|
Now that you have enabled authentication, you are ready to add authorization to your application by using ZITADEL APIs.
|
||||||
|
To do this, [refer to the API docs](/apis/introduction) or check out [the ZITADEL Console code on GitHub](https://github.com/zitadel/zitadel) which uses gRPC to access data.
|
||||||
|
|
||||||
|
For more information on how to create a React application, you can refer to [Create React App](https://github.com/facebook/create-react-app).
|
||||||
|
If you want to learn more about the libraries wrapped by [@zitadel/react](https://www.npmjs.com/package/@zitadel/react), read the docs for [oidc-client-ts](https://github.com/authts/oidc-client-ts).
|
@ -1,118 +0,0 @@
|
|||||||
---
|
|
||||||
title: ZITADEL with React
|
|
||||||
sidebar_label: React
|
|
||||||
---
|
|
||||||
|
|
||||||
This Integration guide shows you the recommended way to integrate **ZITADEL** into your React Application.
|
|
||||||
It demonstrates how to add a user login to your application and fetch some data from the user info endpoint.
|
|
||||||
|
|
||||||
At the end of the guide you should have an application able to login a user and read the user profile.
|
|
||||||
|
|
||||||
## Setup Application and get Keys
|
|
||||||
|
|
||||||
Before we can start building our application we have to do a few configuration steps in ZITADEL Console.
|
|
||||||
You will need to provide some information about your app. We recommend creating a new app to start from scratch. Navigate to your Project and add a new application at the top of the page.
|
|
||||||
Select User Agent and continue. More about the different app types can you find [here](/guides/integrate/oauth-recommended-flows#different-client-profiles).
|
|
||||||
We recommend that you use [Authorization Code](/apis/openidoauth/grant-types#authorization-code) in combination with [Proof Key for Code Exchange](/apis/openidoauth/grant-types#proof-key-for-code-exchange) for all web applications.
|
|
||||||
|
|
||||||
### Redirect URLs
|
|
||||||
|
|
||||||
A redirect URL is a URL in your application where ZITADEL redirects the user after they have authenticated. Set your url to the domain the app will be deployed to or use `http://localhost:3000/` because this will be the default of npm.
|
|
||||||
|
|
||||||
> You should set dev mode to `true` as this will enable unsecure http for the moment.
|
|
||||||
|
|
||||||
If you want to redirect the users back to a route on your application after they have logged out, add an optional redirect in the post redirectURI field.
|
|
||||||
|
|
||||||
Continue and Create the application.
|
|
||||||
|
|
||||||
### Client ID
|
|
||||||
|
|
||||||
After successful app creation a popup will appear showing you your clientID.
|
|
||||||
Copy your client ID as it will be needed in the next step.
|
|
||||||
|
|
||||||
## React Setup
|
|
||||||
|
|
||||||
### Create React app
|
|
||||||
|
|
||||||
Create a new React app with the following command
|
|
||||||
|
|
||||||
```bash
|
|
||||||
npx create-react-app my-app
|
|
||||||
```
|
|
||||||
|
|
||||||
### Install oidc client
|
|
||||||
|
|
||||||
You need to install an oauth / oidc client to connect with ZITADEL. Run the following command:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
npm install oidc-react
|
|
||||||
```
|
|
||||||
|
|
||||||
This library helps integrating ZITADEL Authentication in your React Application.
|
|
||||||
|
|
||||||
### Create and configure Auth Module
|
|
||||||
|
|
||||||
With the installed oidc pakage you will need an AuthProvider which should contain the OIDC configuration.
|
|
||||||
|
|
||||||
The oidc configuration should contain **openid**, **profile** and **email** as scope and **code** as responseType.
|
|
||||||
In the code below make sure to change the issuer to your instance url. You can find this in the ZITADEL Console on you application.
|
|
||||||
Replace the clientId value 'YOUR-CLIENT-ID' with the generated client id of you application in ZITADEL Console.
|
|
||||||
|
|
||||||
```ts
|
|
||||||
import React from "react";
|
|
||||||
import { AuthProvider } from "oidc-react";
|
|
||||||
import "./App.css";
|
|
||||||
const oidcConfig = {
|
|
||||||
onSignIn: async (response: any) => {
|
|
||||||
alert(
|
|
||||||
"You logged in :" +
|
|
||||||
response.profile.given_name +
|
|
||||||
" " +
|
|
||||||
response.profile.family_name
|
|
||||||
);
|
|
||||||
window.location.hash = "";
|
|
||||||
},
|
|
||||||
authority: "https:/[your-domain]-[random-string].zitadel.cloud", // replace with your instance
|
|
||||||
clientId: "YOUR-CLIENT-ID",
|
|
||||||
responseType: "code",
|
|
||||||
redirectUri: "http://localhost:3000/",
|
|
||||||
scope: "openid profile email",
|
|
||||||
};
|
|
||||||
|
|
||||||
function App() {
|
|
||||||
return (
|
|
||||||
<AuthProvider {...oidcConfig}>
|
|
||||||
<div className="App">
|
|
||||||
<header className="App-header">
|
|
||||||
<p>Hello World</p>
|
|
||||||
</header>
|
|
||||||
</div>
|
|
||||||
</AuthProvider>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
export default App;
|
|
||||||
```
|
|
||||||
|
|
||||||
### Run application
|
|
||||||
|
|
||||||
Start your react application with the following command
|
|
||||||
|
|
||||||
```bash
|
|
||||||
npm start
|
|
||||||
```
|
|
||||||
|
|
||||||
Your browser should automatically open the app site or just go to `http://localhost:3000/`.
|
|
||||||
On opening the app in the browser you will be redirected to the login of your instance.
|
|
||||||
After successfully authenticating your user, you will get back to you application.
|
|
||||||
It should show a popup which says: **You logged in {FirstName} {LastName}**
|
|
||||||
|
|
||||||
## Completion
|
|
||||||
|
|
||||||
You have successfully integrated ZITADEL in your React Application!
|
|
||||||
|
|
||||||
### Whats next?
|
|
||||||
|
|
||||||
Now you can proceed implementing our APIs to include Authorization. You can find our API Docs [here](/apis/introduction)
|
|
||||||
|
|
||||||
For more information about creating a React application we refer to [React](https://reactjs.org/docs/getting-started.html) and for more information about the used oauth/oidc library consider reading their docs at [oidc-react](https://www.npmjs.com/package/oidc-react).
|
|
@ -9,17 +9,18 @@ Management for resources.
|
|||||||
|
|
||||||
## ZITADEL SDKs
|
## ZITADEL SDKs
|
||||||
|
|
||||||
| Language / Framework | Link Github | User Authentication | Manage resources | Notes |
|
| Language / Framework | Link Github | User Authentication | Manage resources | Notes |
|
||||||
|----------------------|---------------------------------------------------------------|-----------------------------------------------------------|------------------|-------------------|
|
| -------------------- | ------------------------------------------------------------- | --------------------------------------------------------- | ---------------- | ----------- |
|
||||||
| Go | [zitadel-go](https://github.com/zitadel/zitadel-go) | 🚧 [WIP](https://github.com/zitadel/zitadel-go/tree/next) | ✔️ | `official` |
|
| Go | [zitadel-go](https://github.com/zitadel/zitadel-go) | 🚧 [WIP](https://github.com/zitadel/zitadel-go/tree/next) | ✔️ | `official` |
|
||||||
| Vue | [zitadel-vue](https://github.com/zitadel/zitadel-vue) | ✔️ | ❌ | `official` |
|
| Vue | [zitadel-vue](https://github.com/zitadel/zitadel-vue) | ✔️ | ❌ | `official` |
|
||||||
| .NET | [zitadel-net](https://github.com/smartive/zitadel-net) | ✔️ | ✔️ | `community` |
|
| React | [zitadel-react](https://github.com/zitadel/zitadel-react) | ✔️ | ❌ | `official` |
|
||||||
| Elixir | [zitadel_api](https://github.com/jshmrtn/zitadel_api) | ✔️ | ✔️ | `community` |
|
| .NET | [zitadel-net](https://github.com/smartive/zitadel-net) | ✔️ | ✔️ | `community` |
|
||||||
| NodeJS | [@zitadel/node](https://www.npmjs.com/package/@zitadel/node) | ❌ | ✔️ | `community` |
|
| Elixir | [zitadel_api](https://github.com/jshmrtn/zitadel_api) | ✔️ | ✔️ | `community` |
|
||||||
| Dart | [zitadel-dart](https://github.com/smartive/zitadel-dart) | ❌ | ✔️ | `community` |
|
| NodeJS | [@zitadel/node](https://www.npmjs.com/package/@zitadel/node) | ❌ | ✔️ | `community` |
|
||||||
| Rust | [zitadel-rust](https://github.com/smartive/zitadel-rust) | ✔️ | ✔️ | `community` |
|
| Dart | [zitadel-dart](https://github.com/smartive/zitadel-dart) | ❌ | ✔️ | `community` |
|
||||||
| JVM | 🚧 [WIP](https://github.com/zitadel/zitadel/discussions/3650) | ❓ | ❓ | TBD |
|
| Rust | [zitadel-rust](https://github.com/smartive/zitadel-rust) | ✔️ | ✔️ | `community` |
|
||||||
| Python | 🚧 [WIP](https://github.com/zitadel/zitadel/issues/3675) | ❓ | ❓ | TBD |
|
| JVM | 🚧 [WIP](https://github.com/zitadel/zitadel/discussions/3650) | ❓ | ❓ | TBD |
|
||||||
|
| Python | 🚧 [WIP](https://github.com/zitadel/zitadel/issues/3675) | ❓ | ❓ | TBD |
|
||||||
|
|
||||||
## Missing SDK
|
## Missing SDK
|
||||||
|
|
||||||
|
@ -3,8 +3,6 @@ title: The ZITADEL Quick Start Guide
|
|||||||
sidebar_label: Quick Start Guide
|
sidebar_label: Quick Start Guide
|
||||||
---
|
---
|
||||||
|
|
||||||
import VSCodeFolderView from "../../../static/img/guides/quickstart/vscode1.png";
|
|
||||||
|
|
||||||
## Introduction
|
## Introduction
|
||||||
|
|
||||||
In this quick start guide, we will be learning some fundamentals on how to set up ZITADEL for user management and application security. Thereafter, we will secure a React-based Single Page Application (SPA) using ZITADEL.
|
In this quick start guide, we will be learning some fundamentals on how to set up ZITADEL for user management and application security. Thereafter, we will secure a React-based Single Page Application (SPA) using ZITADEL.
|
||||||
@ -71,103 +69,69 @@ The order of creation for the above components may vary depending on the specifi
|
|||||||
|
|
||||||

|

|
||||||
|
|
||||||
|
|
||||||
2. You can sign up by entering your email address or via social login, e.g., Google. Let's sign up using an email address. Enter your email address and click "Sign in with Email".
|
2. You can sign up by entering your email address or via social login, e.g., Google. Let's sign up using an email address. Enter your email address and click "Sign in with Email".
|
||||||
|
|
||||||

|

|
||||||
|
|
||||||
|
|
||||||
3. Next, complete your details and click "Continue".
|
3. Next, complete your details and click "Continue".
|
||||||
|
|
||||||

|

|
||||||
|
|
||||||
|
|
||||||
4. Add a password as shown below. Adhere to the password requirements, agree to the terms of service and privacy policy by selecting the checkbox, and click the "Get started" button.
|
4. Add a password as shown below. Adhere to the password requirements, agree to the terms of service and privacy policy by selecting the checkbox, and click the "Get started" button.
|
||||||
|
|
||||||

|

|
||||||
|
|
||||||
|
|
||||||
5. Enter your login data. Provide the password you just created. Click "next".
|
5. Enter your login data. Provide the password you just created. Click "next".
|
||||||
|
|
||||||

|

|
||||||
|
|
||||||
|
|
||||||
6. You will now have to verify your email address.
|
6. You will now have to verify your email address.
|
||||||
|
|
||||||

|

|
||||||
|
|
||||||
|
|
||||||
6. Go to your inbox and open the email from ZITADEL and click the "Verify email" button.
|
6. Go to your inbox and open the email from ZITADEL and click the "Verify email" button.
|
||||||
|
|
||||||

|

|
||||||
|
|
||||||
|
|
||||||
7. The user is now activated. Click the "login" button.
|
7. The user is now activated. Click the "login" button.
|
||||||
|
|
||||||

|

|
||||||
|
|
||||||
|
8. Now you will have to log in with the username and password that you provided. Click “Sign in with Email”, then provide a name for your team or organization and continue.
|
||||||
8. Now you will have to log in with the username and password that you provided. Click “Sign in with Email”.
|
|
||||||
|
|
||||||

|

|
||||||
|
|
||||||
|
|
||||||
9. You will now be asked to create an instance.
|
|
||||||
|
|
||||||

|
|
||||||
|
|
||||||
|
|
||||||
### 2. Create your first instance
|
### 2. Create your first instance
|
||||||
|
|
||||||
As a user of the ZITADEL Cloud Customer Portal, you now can create multiple instances to suit your specific needs. This includes instances for development, production, or user acceptance testing, as well as instances for different clients or applications. For example, you might create an instance for each product in a B2C scenario, or an instance for each tenant or customer in a B2B scenario. The possibilities are endless. You can create a pay-as-you-go instance for production purposes.
|
As a user of the ZITADEL Cloud Customer Portal, you now can create multiple instances to suit your specific needs. This includes instances for development, production, or user acceptance testing, as well as instances for different clients or applications. For example, you might create an instance for each product in a B2C scenario, or an instance for each tenant or customer in a B2B scenario. The possibilities are endless. You can create your first instance for free.
|
||||||
|
|
||||||
1. Let’s create an instance. Click on “Create new instance”.
|
1. Let’s create an instance. Click on “Create new instance”.
|
||||||
|
|
||||||

|

|
||||||
|
|
||||||
|
2. Provide a name for your instance and click on the “Continue” button at the bottom of this screen.
|
||||||
|
|
||||||
2. Provide a name for your instance, select the “Free” plan and click on the “Continue” button at the bottom of this screen.
|
|
||||||
|
|
||||||

|

|
||||||
|
|
||||||
|
|
||||||
3. Next, you should see the following screen. Add a username and password for the instance manager and click "Create".
|
3. Next, you should see the following screen. Add a username and password for the instance manager and click "Create".
|
||||||
|
|
||||||
|
|
||||||

|

|
||||||
|
|
||||||
|
3. Now you will see the details of your first instance. You can click on "Visit" at the top right to go to your instance.
|
||||||
4. The instance creation process will take a few seconds.
|
|
||||||
|
|
||||||

|

|
||||||
|
|
||||||
|
6. To log in to your instance, provide the username and password you set in the instance creation, and click “next”.
|
||||||
5. Now you will see the details of your first instance. You can click on "Visit" at the top right to go to your instance.
|
|
||||||
|
|
||||||

|
|
||||||
|
|
||||||
|
|
||||||
6. To log in to your instance, provide the username and password, and click “next”.
|
|
||||||
|
|
||||||

|
|
||||||
|
|
||||||
|
|
||||||
7. Skip the 2-factor authentication for now by clicking “skip”.
|
7. Skip the 2-factor authentication for now by clicking “skip”.
|
||||||
|
|
||||||

|
|
||||||
|
|
||||||
8. And there you go! You now have access to your instance.
|
8. And there you go! You now have access to your instance.
|
||||||
|
|
||||||

|

|
||||||
|
|
||||||
|
|
||||||
### 3. Create your first project
|
### 3. Create your first project
|
||||||
|
|
||||||
1. To create a project in the instance you just created, click on “Create a project”.
|
1. To create a project in the instance you just created, click on "Projects" in the navigation and then “Create a project”.
|
||||||
|
|
||||||

|
|
||||||
|
|
||||||
|
|
||||||
2. Insert “Project1” (or any name of your choice) as the project’s name and click the “Continue” button.
|
2. Insert “Project1” (or any name of your choice) as the project’s name and click the “Continue” button.
|
||||||
|
|
||||||
@ -343,315 +307,84 @@ To install Visual Studio Code, go to their [website](https://code.visualstudio.c
|
|||||||
2. Navigate to the folder where you want to create the React app.
|
2. Navigate to the folder where you want to create the React app.
|
||||||
3. Run the following command to create a new React app named "react-oidc-zitadel":
|
3. Run the following command to create a new React app named "react-oidc-zitadel":
|
||||||
|
|
||||||
`npx create-react-app react-oidc-zitadel`
|
`yarn create react-app react-oidc-zitadel --template typescript`
|
||||||
|
|
||||||
4. Navigate to the "react-oidc-zitadel" folder:
|
4. Navigate to the "react-oidc-zitadel" folder:
|
||||||
|
|
||||||
`cd react-oidc-zitadel`
|
`cd react-oidc-zitadel`
|
||||||
|
|
||||||
This will create the following files in your project:
|
5. The dependencies for this project include @zitadel/react and react-router-dom. To include them in your React application, you will need to run the following command in your terminal:
|
||||||
|
|
||||||
<img src={VSCodeFolderView} width="40%" height="40%" />
|
`yarn add @zitadel/react react-router-dom`
|
||||||
|
|
||||||
5. The dependencies for this project include react-router-dom and oidc-client-ts. To include them in your React application, you will need to run the following command in your terminal:
|
|
||||||
|
|
||||||
`npm install react-router-dom oidc-client-ts`
|
|
||||||
|
|
||||||
#### 2. Add source files
|
#### 2. Add source files
|
||||||
|
|
||||||
The code needed to run this project can be found [here](https://github.com/zitadel/react-user-authentication).
|
The code needed to run this project can be found [here](https://github.com/zitadel/zitadel-react).
|
||||||
|
|
||||||
1. Replace the content in your App.js file with the one provided below:
|
1. Replace the content in your App.js file with the one provided below:
|
||||||
|
|
||||||
[src/App.js](https://github.com/zitadel/react-user-authentication/blob/main/src/App.js):
|
[src/App.tsx](https://github.com/zitadel/zitadel-react/blob/main/src/App.tsx):
|
||||||
|
|
||||||
```
|
```
|
||||||
import React, { useState, useEffect } from "react";
|
const config: ZitadelConfig = {
|
||||||
import { BrowserRouter, Routes, Route } from "react-router-dom";
|
authority: "[YOUR-INSTANCE-URL]",
|
||||||
import Login from "./components/Login";
|
client_id: "[YOUR-CLIENT-ID]",
|
||||||
import Callback from "./components/Callback";
|
};
|
||||||
import authConfig from "./authConfig";
|
|
||||||
import { UserManager, WebStorageStateStore } from "oidc-client-ts";
|
|
||||||
|
|
||||||
function App() {
|
const zitadel = createZitadelAuth(config);
|
||||||
const userManager = new UserManager({
|
...
|
||||||
userStore: new WebStorageStateStore({ store: window.localStorage }),
|
|
||||||
...authConfig,
|
|
||||||
});
|
|
||||||
|
|
||||||
function authorize() {
|
|
||||||
userManager.signinRedirect({ state: "a2123a67ff11413fa19217a9ea0fbad5" });
|
|
||||||
}
|
|
||||||
|
|
||||||
function clearAuth() {
|
|
||||||
userManager.signoutRedirect();
|
|
||||||
}
|
|
||||||
|
|
||||||
const [authenticated, setAuthenticated] = useState(null);
|
|
||||||
const [userInfo, setUserInfo] = useState(null);
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
userManager.getUser().then((user) => {
|
|
||||||
if (user) {
|
|
||||||
setAuthenticated(true);
|
|
||||||
} else {
|
|
||||||
setAuthenticated(false);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}, [userManager]);
|
|
||||||
|
|
||||||
return (
|
|
||||||
<BrowserRouter>
|
|
||||||
<Routes>
|
|
||||||
<Route
|
|
||||||
path="/"
|
|
||||||
element={<Login auth={authenticated} handleLogin={authorize} />}
|
|
||||||
/>
|
|
||||||
<Route
|
|
||||||
path="/callback"
|
|
||||||
element={
|
|
||||||
<Callback
|
|
||||||
auth={authenticated}
|
|
||||||
setAuth={setAuthenticated}
|
|
||||||
userInfo={userInfo}
|
|
||||||
setUserInfo={setUserInfo}
|
|
||||||
handleLogout={clearAuth}
|
|
||||||
userManager={userManager}
|
|
||||||
/>
|
|
||||||
}
|
|
||||||
/>
|
|
||||||
</Routes>
|
|
||||||
</BrowserRouter>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
export default App;
|
|
||||||
```
|
```
|
||||||
|
|
||||||
The App.js file is the root component of the React app that initializes the OIDC flow and manages the user's session. It does this by:
|
The App.tsx file is the root component of the React app that initializes the OIDC flow and manages the user's session. It does this by:
|
||||||
|
|
||||||
- Importing the necessary libraries and components from the dependencies, including the `oidc-client-ts` library, the `authConfig` file with the OIDC configuration values, and the Login and Callback components.
|
- Importing the necessary libraries and components from the dependencies, including the `@zitadel/react` library and the Login and Callback components.
|
||||||
- Initializing a new `UserManager` instance with the OIDC configuration values from the authConfig file. The ` UserManager` instance manages the OIDC flow and stores the user's session information.
|
- Initializing a new `zitadel` instance with the OIDC configuration values. The `zitadel` instance manages the OIDC flow and stores the user's session information.
|
||||||
- Defining two functions: `authorize` and `clearAuth`. The `authorize` function initiates the OIDC flow when the user clicks the `login` button, while the `clearAuth` function ends the user's session when the user clicks the `logout` button.
|
- Defining two functions: `authorize` and `signout`. The `authorize` function initiates the OIDC flow when the user clicks the `login` button, while the `signout` function ends the user's session when the user clicks the `logout` button.
|
||||||
- Defining two state variables: `authenticated` and `userInfo`. The authenticated variable is a boolean that indicates whether the user is authenticated or not, while the `userInfo` variable stores the user's information when they are authenticated.
|
- Defining state variable: `authenticated`. The authenticated variable is a boolean that indicates whether the user is authenticated or not.
|
||||||
- Using the `useEffect` hook to retrieve the user's session information from the `UserManager` instance and updating the `authenticated` and `userInfo` state variables accordingly.
|
- Using the `useEffect` hook to retrieve the user's session information from the `UserManager` instance and updating the `authenticated` state variable accordingly.
|
||||||
- Defining the routes for the app using the `react-router-dom` library, including the `/` and `/callback` routes for the login and callback pages, respectively. The `Login` and `Callback` components handle the login and callback processes, respectively.
|
- Defining the routes for the app using the `react-router-dom` library, including the `/` and `/callback` routes for the login and callback pages, respectively. The `Login` and `Callback` components handle the login and callback processes, respectively.
|
||||||
|
|
||||||
|
The provided config extends the `UserManagerSettings` of the `oidc-client-ts` library. Take a look at some of the available configuration options:
|
||||||
|
|
||||||
|
- authority (the URL of your instance ending with /).
|
||||||
|
- client\*id (the unique identifier for the client application).
|
||||||
|
- redirect_uri (the URL to redirect to after the authorization flow is complete)
|
||||||
|
- post_logout_redirect_uri (the URL to redirect to after the user logs out)
|
||||||
|
- scope (the permissions requested from the user)
|
||||||
|
- project_resource_id (To add a ZITADEL project scope. `urn:zitadel:iam:org:project:id:[projectId]:aud` and `urn:zitadel:iam:org:projects:roles` [scopes](https://zitadel.com/docs/apis/openidoauth/scopes#reserved-scopes).)
|
||||||
|
- prompt ([the OIDC prompt parameter](http://localhost:3000/docs/apis/openidoauth/endpoints#additional-parameters))
|
||||||
|
|
||||||
2. Create a folder named components in the src directory. Create two files named Login.js and Callback.js.
|
2. Create a folder named components in the src directory. Create two files named Login.js and Callback.js.
|
||||||
|
|
||||||
3. Paste the following code to Login.js.
|
3. Paste the following code to Login.tsx.
|
||||||
|
|
||||||
[src/components/Login.js](https://github.com/zitadel/react-user-authentication/blob/main/src/components/Login.js)
|
```ts reference
|
||||||
|
https://github.com/zitadel/zitadel-react/blob/main/src/components/Login.tsx
|
||||||
```
|
|
||||||
import { Navigate } from "react-router-dom";
|
|
||||||
|
|
||||||
const Login = ({ auth, handleLogin, userManager }) => {
|
|
||||||
return (
|
|
||||||
<div>
|
|
||||||
{auth === null && <div>Loading...</div>}
|
|
||||||
{auth === false && (
|
|
||||||
<div>
|
|
||||||
<h1>Welcome!</h1>
|
|
||||||
<button
|
|
||||||
onClick={() => {
|
|
||||||
// Perform the authorization request, including the code challenge
|
|
||||||
handleLogin();
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
Please log in.
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
{auth && <Navigate to="/callback" />}
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
};
|
|
||||||
|
|
||||||
export default Login;
|
|
||||||
```
|
```
|
||||||
|
|
||||||
The `/` route corresponds to the login page, which is rendered by the Login component. The Login(Login.js) component is a functional component that displays the login button and calls the `handleLogin` function (which corresponds to the `authorize` function defined in the App component) when the button is clicked. This initiates the OIDC flow by redirecting the user to the authorization endpoint.
|
The `/` route corresponds to the login page, which is rendered by the Login component. The Login(Login.tsx) component is a functional component that displays the login button and calls the `handleLogin` function (which corresponds to the `authorize` function defined in the App component) when the button is clicked. This initiates the OIDC flow by redirecting the user to the authorization endpoint.
|
||||||
|
|
||||||
4. Paste the following code to Callback.js.
|
4. Paste the following code to Callback.js.
|
||||||
|
|
||||||
[src/components/Callback.js](https://github.com/zitadel/react-user-authentication/blob/main/src/components/Callback.js)
|
```ts reference
|
||||||
|
https://github.com/zitadel/zitadel-react/blob/main/src/components/Callback.tsx
|
||||||
```
|
|
||||||
import React, { useEffect } from 'react';
|
|
||||||
import authConfig from '../authConfig';
|
|
||||||
|
|
||||||
const Callback = ({ auth, setAuth, userManager, userInfo, setUserInfo, handleLogout }) => {
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
if (auth === null) {
|
|
||||||
userManager.signinRedirectCallback().then((user) => {
|
|
||||||
if (user) {
|
|
||||||
setAuth(true);
|
|
||||||
const access_token = user.access_token;
|
|
||||||
// Make a request to the user info endpoint using the access token
|
|
||||||
fetch(authConfig.userinfo_endpoint, {
|
|
||||||
headers: {
|
|
||||||
'Authorization': `Bearer ${access_token}`
|
|
||||||
}
|
|
||||||
})
|
|
||||||
.then(response => response.json())
|
|
||||||
.then(userInfo => {
|
|
||||||
setUserInfo(userInfo);
|
|
||||||
});
|
|
||||||
} else {
|
|
||||||
setAuth(false);
|
|
||||||
}
|
|
||||||
}).catch((error) => {
|
|
||||||
setAuth(false);
|
|
||||||
});
|
|
||||||
} else if (auth === true && !userInfo) {
|
|
||||||
userManager.getUser().then((user) => {
|
|
||||||
const access_token = user.access_token;
|
|
||||||
|
|
||||||
fetch(authConfig.userinfo_endpoint, {
|
|
||||||
headers: {
|
|
||||||
Authorization: `Bearer ${access_token}`,
|
|
||||||
},
|
|
||||||
})
|
|
||||||
.then((response) => response.json())
|
|
||||||
.then((userInfo) => {
|
|
||||||
setUserInfo(userInfo);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}, [auth, userManager, setAuth]);
|
|
||||||
|
|
||||||
|
|
||||||
if (auth === true && userInfo) {
|
|
||||||
return (
|
|
||||||
<div>
|
|
||||||
<h1>Welcome, {userInfo.name}!</h1>
|
|
||||||
<h2>Your ZITADEL Profile Information</h2>
|
|
||||||
<h3>Name: {userInfo.name}</h3>
|
|
||||||
<h3>Email: {userInfo.email}</h3>
|
|
||||||
<h3>Email Verified: {userInfo.email_verified? "Yes": "No"}</h3>
|
|
||||||
<h3>Locale: {userInfo.locale}</h3>
|
|
||||||
|
|
||||||
<button onClick={handleLogout}>Log out</button>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
else {
|
|
||||||
return <div>Loading...</div>;
|
|
||||||
}
|
|
||||||
|
|
||||||
};
|
|
||||||
|
|
||||||
export default Callback;
|
|
||||||
```
|
```
|
||||||
|
|
||||||
The `/callback` route corresponds to the callback page, which is rendered by the Callback(Callback.js) component. The Callback component is also a functional component that handles the callback from the authorization server after the user logs in. It retrieves the authorization code from the URL, exchanges it for an access token and id token, and retrieves the user's information from the userinfo endpoint. It also sets the `authenticated` and `userInfo` state variables in the App(App.js) component and displays the `logout` button. When the `logout` button is clicked, the `clearAuth` function is called and the user's session is ended. The `clearAuth` function is defined in the App component and is called with no arguments. It initiates the end session flow by redirecting the user to the end session endpoint.
|
The `/callback` route corresponds to the callback page, which is rendered by the Callback (Callback.tsx) component.
|
||||||
|
The Callback component is also a functional component that handles the callback from the authorization server after the user logs in.
|
||||||
|
It retrieves the authorization code from the URL, exchanges it for an access token and id token, and retrieves the user's information from the userinfo endpoint.
|
||||||
|
It also sets the `authenticated` state variable in the App (App.tsx) component and displays the `logout` button.
|
||||||
|
When the `logout` button is clicked, the `clearAuth` function is called and the user's session is ended. The `clearAuth` function is defined in the App component and is called with no arguments. It initiates the end session flow by redirecting the user to the end session endpoint.
|
||||||
|
|
||||||
5. Create a new file in the src folder named authConfig.js and paste the following code to it.
|
Note that the @zitadel/react library automatically handles the generation of the code verifier and code challenge when the user clicks on the login button, eliminating the need for the application to manually generate and include these values in the requests.
|
||||||
|
|
||||||
[src/authConfig.js](https://github.com/zitadel/react-user-authentication/blob/main/src/authConfig.js)
|
|
||||||
|
|
||||||
```
|
|
||||||
const authConfig = {
|
|
||||||
authority: 'https://some_text.zitadel.cloud/', //Replace with your issuer URL
|
|
||||||
client_id: 'ABC123@Project', //Replace with your client id
|
|
||||||
redirect_uri: 'http://localhost:3000/callback',
|
|
||||||
response_type: 'code',
|
|
||||||
scope: 'openid profile email',
|
|
||||||
post_logout_redirect_uri: 'http://localhost:3000/',
|
|
||||||
userinfo_endpoint: 'https://instance-some_text.zitadel.cloud/oidc/v1/userinfo', //Replace with your user-info endpoint
|
|
||||||
response_mode: 'query',
|
|
||||||
code_challenge_method: 'S256',
|
|
||||||
};
|
|
||||||
|
|
||||||
export default authConfig;
|
|
||||||
```
|
|
||||||
|
|
||||||
The authConfig.js file exports an object with configuration values for the OIDC flow. These values are used to initialize the `UserManager` instance in the App component. The configuration values include the:
|
|
||||||
|
|
||||||
- authority (the URL of the authorization server). **_Don’t forget to replace the `authority` value with the “issuer URL” that you obtained from this [step](#referred1)._**
|
|
||||||
- client_id (the unique identifier for the client application). **_Don’t forget to replace the `client_id` with your “ClientId” that you obtained from this [step](#referred1)._**
|
|
||||||
- redirect_uri (the URL to redirect to after the authorization flow is complete)
|
|
||||||
- response_type (the type of response expected from the authorization server)
|
|
||||||
- scope (the permissions requested from the user)
|
|
||||||
- post_logout_redirect_uri (the URL to redirect to after the user logs out)
|
|
||||||
- userinfo_endpoint (the URL of the endpoint to retrieve the user's information). **_Don’t forget to replace the `userinfo_endoint` with your “userinfo_endpoint” that you obtained from this [step](#referred1)._**
|
|
||||||
- response_mode (the method to use to send the authorization response)
|
|
||||||
- code_challenge_method (the method to use to generate the code challenge).
|
|
||||||
|
|
||||||
Note that the oidc-client-ts library automatically handles the generation of the code verifier and code challenge when the user clicks on the login button, eliminating the need for the application to manually generate and include these values in the requests.
|
|
||||||
|
|
||||||
In the PKCE flow, the code verifier is a random string generated by the client application, and the code challenge is a transformed version of the code verifier using the SHA-256 hashing algorithm.
|
In the PKCE flow, the code verifier is a random string generated by the client application, and the code challenge is a transformed version of the code verifier using the SHA-256 hashing algorithm.
|
||||||
|
|
||||||
6. Add a file called style.css to the src folder to apply CSS styling to the pages.
|
5. Now you can think about styling your application. Edit the `index.css` and `App.css` to apply CSS styling to the pages.
|
||||||
|
|
||||||
[src/style.css](https://github.com/zitadel/react-user-authentication/blob/main/src/style.css)
|
### 3. Running the application
|
||||||
|
|
||||||
```
|
1. Run `yarn start` to start the development server.
|
||||||
/* The body element covers the entire page, so setting the background color here
|
|
||||||
will set the background color for the whole page */
|
|
||||||
body {
|
|
||||||
font-family: 'Open Sans', sans-serif;
|
|
||||||
/* The hex code for the light blue color from the image is #9fd3e0 */
|
|
||||||
background-color: #9fd3e0;
|
|
||||||
/* Center the text in the body element */
|
|
||||||
text-align: center;
|
|
||||||
}
|
|
||||||
|
|
||||||
/* The h1, h2, and h3 elements are used for headings */
|
|
||||||
h1, h2, h3 {
|
|
||||||
/* The hex code for the dark blue color from the image is #2c3e50 */
|
|
||||||
color: #2c3e50;
|
|
||||||
text-align: center;
|
|
||||||
}
|
|
||||||
|
|
||||||
/* The button element represents a clickable button */
|
|
||||||
button {
|
|
||||||
/* The hex code for the light purple color from the image is #9b59b6 */
|
|
||||||
background-color: #9b59b6;
|
|
||||||
/* The hex code for the white color is #ffffff */
|
|
||||||
color: #ffffff;
|
|
||||||
/* Add some padding and a border to the button */
|
|
||||||
padding: 10px 20px;
|
|
||||||
border: none;
|
|
||||||
/* Add some hover effect to the button */
|
|
||||||
cursor: pointer;
|
|
||||||
}
|
|
||||||
|
|
||||||
button:hover {
|
|
||||||
/* The hex code for the dark purple color from the image is #8e44ad */
|
|
||||||
background-color: #8e44ad;
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
7. Go to index.js and replace `import './index.css';` with `import './style.css'`. Your index.js file should look like this:
|
|
||||||
|
|
||||||
[src/index.js](https://github.com/zitadel/react-user-authentication/blob/main/src/index.js)
|
|
||||||
|
|
||||||
```
|
|
||||||
import React from 'react';
|
|
||||||
import ReactDOM from 'react-dom/client';
|
|
||||||
import './style.css';
|
|
||||||
import App from './App';
|
|
||||||
import reportWebVitals from './reportWebVitals';
|
|
||||||
|
|
||||||
const root = ReactDOM.createRoot(document.getElementById('root'));
|
|
||||||
root.render(
|
|
||||||
<React.StrictMode>
|
|
||||||
<App />
|
|
||||||
</React.StrictMode>
|
|
||||||
);
|
|
||||||
|
|
||||||
// If you want to start measuring performance in your app, pass a function
|
|
||||||
// to log results (for example: reportWebVitals(console.log))
|
|
||||||
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
|
|
||||||
reportWebVitals();
|
|
||||||
```
|
|
||||||
|
|
||||||
### 4. Running the application
|
|
||||||
|
|
||||||
1. Run `npm start` to start the development server.
|
|
||||||
2. Open your browser and navigate to `http://localhost:3000/` to view the app.
|
2. Open your browser and navigate to `http://localhost:3000/` to view the app.
|
||||||
3. You will see the login page, which is the landing page of the app, when you run the application. Click on the “Please log in” button.
|
3. You will see the login page, which is the landing page of the app, when you run the application. Click on the “Please log in” button.
|
||||||
|
|
||||||
@ -673,14 +406,6 @@ reportWebVitals();
|
|||||||
|
|
||||||

|

|
||||||
|
|
||||||
8. To see if the user has been successfully logged out and the user session has been terminated, click on “Please log in”, which brings you to the following page. Select the same user you logged in with earlier.
|
|
||||||
|
|
||||||

|
|
||||||
|
|
||||||
9. You will see that since the login session was terminated after logging out, the user has to enter his password again.
|
|
||||||
|
|
||||||

|
|
||||||
|
|
||||||
And this brings us to the end of this quick start guide!
|
And this brings us to the end of this quick start guide!
|
||||||
|
|
||||||
This tutorial covered how to configure ZITADEL and how to use React to build an app that communicates with ZITADEL to access secured resources.
|
This tutorial covered how to configure ZITADEL and how to use React to build an app that communicates with ZITADEL to access secured resources.
|
||||||
|
BIN
docs/static/img/guides/quickstart/login1.png
vendored
Before Width: | Height: | Size: 113 KiB After Width: | Height: | Size: 167 KiB |
BIN
docs/static/img/guides/quickstart/login2.png
vendored
Before Width: | Height: | Size: 144 KiB After Width: | Height: | Size: 87 KiB |
BIN
docs/static/img/guides/quickstart/login3.png
vendored
Before Width: | Height: | Size: 136 KiB After Width: | Height: | Size: 99 KiB |
BIN
docs/static/img/guides/quickstart/login4.png
vendored
Before Width: | Height: | Size: 612 KiB After Width: | Height: | Size: 217 KiB |
BIN
docs/static/img/guides/quickstart/login5.png
vendored
Before Width: | Height: | Size: 169 KiB |
BIN
docs/static/img/guides/quickstart/login6.png
vendored
Before Width: | Height: | Size: 155 KiB |
BIN
docs/static/img/guides/quickstart/v3_10.png
vendored
Before Width: | Height: | Size: 282 KiB After Width: | Height: | Size: 142 KiB |
BIN
docs/static/img/guides/quickstart/v3_11.png
vendored
Before Width: | Height: | Size: 280 KiB After Width: | Height: | Size: 228 KiB |
BIN
docs/static/img/guides/quickstart/v3_12.png
vendored
Before Width: | Height: | Size: 298 KiB After Width: | Height: | Size: 229 KiB |
BIN
docs/static/img/guides/quickstart/v3_13.png
vendored
Before Width: | Height: | Size: 289 KiB |
BIN
docs/static/img/guides/quickstart/v3_14.png
vendored
Before Width: | Height: | Size: 182 KiB |
BIN
docs/static/img/guides/quickstart/v3_15.png
vendored
Before Width: | Height: | Size: 221 KiB |
BIN
docs/static/img/guides/quickstart/v3_9.png
vendored
Before Width: | Height: | Size: 215 KiB After Width: | Height: | Size: 316 KiB |
BIN
docs/static/img/guides/quickstart/vscode1.png
vendored
Before Width: | Height: | Size: 89 KiB |
BIN
docs/static/img/react/app-create.png
vendored
Normal file
After Width: | Height: | Size: 230 KiB |
BIN
docs/static/img/react/app-screen.png
vendored
Normal file
After Width: | Height: | Size: 243 KiB |
BIN
docs/static/img/react/project-authz.png
vendored
Normal file
After Width: | Height: | Size: 286 KiB |
BIN
docs/static/img/react/project-role.png
vendored
Normal file
After Width: | Height: | Size: 272 KiB |