Coder Social home page Coder Social logo

fusionauth / fusionauth-example-react-sdk Goto Github PK

View Code? Open in Web Editor NEW
2.0 14.0 8.0 40.43 MB

Example of using FusionAuth with the react SDK.

Home Page: https://fusionauth.io/docs/quickstarts/#single-page-app

License: Apache License 2.0

JavaScript 20.95% HTML 2.95% TypeScript 12.11% SCSS 7.13% CSS 56.86%
authorization-code-grant example fusionauth oauth2 oidc react sdk hacktoberfest

fusionauth-example-react-sdk's Introduction

Example: Using React and the FusionAuth React SDK

This repository contains example usage of the FusionAuth React SDK. It provides an example React client that uses the SDK, and an example Express server that is used to complete the OAuth token exchange.

If you'd rather use a hosted backend, with no need to use the Express server, please visit our React sample application with the hosted backend repo.

Overview

This example repo consists of two parts:

  • client contains the React client application code which utilizes the FusionAuth React SDK
  • server contains an Express server app which is used to securely perform the token exchange

The React client shows example usage of the SDK and integrates with React Router v6.

Screenshot of the example application login screen

Setup

Prerequisites

  • Yarn: This will be needed for pulling down the various dependencies.
  • NodeJS: This will be used in order to run the node server.
  • FusionAuth: This is the auth server. Install in one of two ways:

FusionAuth Setup

You can do this one of two ways, using Docker and Kickstart or manually by logging into the FusionAuth administrative user interface.

Docker

If you run FusionAuth from a Docker container, in the root of this project directory (next to this README) are two files a Docker compose file and an environment variables configuration file. Assuming you have Docker installed on your machine, a docker-compose up will bring FusionAuth up on your machine.

The FusionAuth configuration files also make use of a unique feature of FusionAuth, called Kickstart: when FusionAuth comes up for the first time, it will look at the Kickstart file and mimic API calls to configure FusionAuth for use. It will perform all the necessary setup to make this demo work correctly, but if you are curious as to what the setup would look like by hand, the "FusionAuth configuration (by hand)" section of this README describes it in detail.

For now, get FusionAuth in Docker up and running (via docker-compose up) if it is not already running; to see, click here to verify it is up and running.

NOTE: If you ever want to reset the FusionAuth system, delete the volumes created by docker-compose by executing docker-compose down -v. FusionAuth will only apply the Kickstart settings when it is first run (e.g., it has no data configured for it yet).

If you are using Docker:

  • Your client Id is: e9fdb985-9173-4e01-9d73-ac2d60d1dc8e
  • Your client secret is: super-secret-secret-that-should-be-regenerated-for-production
  • Your example username is [email protected] and your password is password.
  • Your admin username is [email protected] and your password is password.
  • Your fusionAuthBaseUrl is 'http://localhost:9011/'

You can log into the FusionAuth admin UI and look around if you want, but with Docker/Kickstart you don't need to.

You're all done with FusionAuth setup. Skip ahead to the Express Server Setup section.

Manual Configuration

Log into the FusionAuth admin UI.

Go to the Applications section.

  • Create an Application using the green button.
  1. Give it a name
  • On the OAuth tab:
  1. Make sure the authorization code grant is enabled
  2. Add the following to the authorized redirect URLs for your application: http://localhost:3000 and http://localhost:9000/app/callback
  3. Add the following to the authorized request origins URLs for your application: http://localhost:9000
  4. Add the following to the logout URL: http://localhost:3000
  5. Click save.
  6. Edit the application again.
  7. Record the client Id and secret, you'll use that below.
  • On the registration tab, ensure self service registration is enabled.

  • Save the application again.

Go to the Users section.

  • Create a user if needed.

Go to the Themes section, under Customization.

  1. Duplicate the FusionAuth theme.
  2. Provide a name, such as 'React theme'.
  3. Copy the contents of the file at kickstart/css/styles.css into the styles theme field.
  4. Save the theme.

Go to the Tenants section.

  1. Edit the default tenant
  2. On the General tab, update the tenant theme to be your new theme; 'React theme' if you used that name.
  3. Save the tenant.

Go to the Settings -> System -> CORS

  1. Set enable cors true.
  2. Set allowed credentials true.
  3. Set allowed methods GET POST OPTIONS.
  4. Set allowed origins http://localhost:3000

FusionAuth is all set up. Proceed to the Express Server Setup section.

Express Server Setup

From the server directory:

  1. Update config.js if you aren't using docker/kickstart
  2. Run yarn install to install dependencies
  3. Run yarn start to start the server at http://localhost:9000

React Client Setup

From the client directory:

  1. Update src/config.ts if you aren't using docker/kickstart
  2. Run yarn install to install dependencies
  3. Run yarn start to start your React app at http://localhost:3000

Test It Out

Visit the React app. You should be able to log in, log out and register a new user.

SDK Examples

Three files in particular demonstrate the usage of the SDK. Check out the following:

  • client/src/FusionAuthProviderWithRedirectHandling.tsx - custom redirect handling to integrate with React Router
  • client/src/pages/LoginPage.tsx - a simple login page that pulls loading/authentication state out of FusionAuth context via useFusionAuth() as well as the out-of-the-box Login and Register buttons
  • client/src/pages/AccountPage.tsx - a simple account page that
    • wraps page in RequireAuth component to protect information from unauthorized users.
    • pulls user state from the FusionAuth context via useFusionAuth() to display information about the authenticated user

Server Endpoint Requirements

The server you configure to use with the React SDK must have a /token-exchange endpoint to perform the exchange, a /logout endpoint to clear tokens, and optionally a /jwt-refresh endpoint if you wish to use refresh tokens.

You can check out server/routes/token-exchange.js, server/routes/logout.js, and server/routes/jwt-refresh.js to see how these endpoints are implemented. (Note: the Known Issue of multiple requests made to token-exchange may return 503 responses. These can be ignored.)

At a high level:

  • token-exchange.js calls out to the FusionAuth OAuth Token endpoint to get an access token and refresh token, which are both stored in secure cookies
  • jwt-refresh.js calls out to the FusionAuth JWT Refresh endpoint to exchange the refresh token for a new access token
  • logout.js clears the access token and refresh tokens

See the SDK Server Code Requirements for more detail.

fusionauth-example-react-sdk's People

Contributors

aaron-ritter avatar alex-fusionauth avatar bhalsey avatar dmackinn avatar jakelo123 avatar jpdeblock avatar mark-robustelli avatar mooreds avatar sam-woodridge avatar

Stargazers

 avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

fusionauth-example-react-sdk's Issues

Yarn install falls

(dep PR might resolve, not sure) #21

โฏ yarn install
yarn install v1.22.19
[1/4] ๐Ÿ”  Resolving packages...
[2/4] ๐Ÿšš  Fetching packages...
error [email protected]: The engine "node" is incompatible with this module. Expected version "^14.15.0 || ^16.10.0 || >=18.0.0". Got "15.14.0"
error Found incompatible module.
info Visit https://yarnpkg.com/en/docs/cli/install for documentation about this command.

Possibly resolved by pull request. This is with a fresh clone and install of this repo.

Ability to provide a idp_hint parameter

I've configured a custom Idp in fusion auth that I would like to use for login in my app.
I do not want to see the Fusion Auth hosted login page and need the user redirected to the Idp for him to put his credentials.
It looks like the Identity Provider hints is what I want to use as described here : https://fusionauth.io/docs/lifecycle/authenticate-users/identity-providers/#hints
So from what I understand I would need to append a query parameter like &idp_hint=44449786-3dff-42a6-aac6-1f1ceecb6c46 when I get redirected to my login page.
The problem is that this package login options do not contain that option. I can only see the following :

export interface IFusionAuthContext {
    login: (state?: string) => Promise<void>;  <------------- the login function called from my React UI only takes a state param
    logout: () => Promise<void>;
    register: (state?: string) => Promise<void>;
    user: Record<string, any>;
    isLoading: boolean;
    isAuthenticated: boolean;
    refreshToken: () => Promise<void>;
}
...
export interface FusionAuthConfig extends PropsWithChildren {.  <-------------- No other params to specify additional query params for the login URL
    clientID: string;
    serverUrl: string;
    redirectUri: string;
    onRedirectSuccess?: RedirectSuccess;
    onRedirectFail?: RedirectFail;
    scope?: string;
    accessTokenExpireWindow?: number;
    loginPath?: string;
    logoutPath?: string;
    registerPath?: string;
    tokenRefreshPath?: string;
    mePath?: string;
}

So is there another way for me to add such a parameter ? Or is it a case where I need to provide a custom backend myself ?

Thanks

request http client is deprecated

request http client is deprecated

Problem

The http client used by the server -- request -- was fully deprecated in 2020.

Solution

Remove the dependency and either replace the functionality relies on it.
Alternatives:

Alternatives/workarounds

Continue using the deprecated dependency.

Hacktoberfest: Update Dependencies

Verify that the application(s) will work when updating package.json to the latest versions.

Find outdated packages

npm outdated

Update to latest

npx npm-check-updates -u
npm install

Verify application is still functioning by running through README.md and associated documentation.

Please note it may not always make sense to update everything, please mention what if anything went wrong in the PR.

Need more robust error handling in token-exchange and jwt-refresh.

The token-exchange and jwt-refresh endpoints currently return a 5xx response if not in the happy path. The endpoints should handle the various error codes that can be returned with appropriate response codes that help the developer understand the underlying issue (e.g., misconfiguration, bad user request, etc.).

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.