npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@asgardeo/auth-react

v5.2.3

Published

Asgardeo Auth React SDK for React Applications.

Downloads

5,053

Readme

Asgardeo Auth React SDK

Builder Stackoverflow Join the chat at https://discord.gg/wso2 License Twitter


Table of Content

Introduction

Asgardeo Auth React SDK allows React applications to use OpenID Connect - OIDC authentication with Asgardeo as the Consumer Identity and Access Management(CIAM) Provider. The SDK supports following capabilities

Prerequisite - Register your application in Asgardeo

  1. Register to Asgardeo and create an organization if you don't already have one. The organization name you choose will be referred to as <org_name> throughout this document.
  2. Register a Single Page Application in Asgardeo to obtain necessary keys to integrate your application with Asgardeo. You will obtain a client_ID from Asgardeo for your application which will need to embed later in your application for the integration.

Getting Started

Follow this guide to integrate Asgardeo to your own React Application. To try out the sample apps, use this guide.

1. Installing the Package

Run the following command to install @asgardeo/auth-react from the npm registry.

npm install @asgardeo/auth-react --save

2. Import AuthProvider and Provide Configuration Parameters

Asgardeo React SDK exposes the AuthProvider component, which helps you easily integrate Asgardeo to your application.

First, import the AuthProvider component from @asgardeo/auth-react. where you applications root component is defined.

Note Typically the root component of a react app is defined in the index.* file.

import { AuthProvider } from "@asgardeo/auth-react";

Then, wrap your root component with the AuthProvider.

import React from "react";
import { AuthProvider } from "@asgardeo/auth-react";

const config = {
     signInRedirectURL: "https://localhost:3000/sign-in",
     signOutRedirectURL: "https://localhost:3000/dashboard",
     clientID: "<client_ID>",
     baseUrl: "https://api.asgardeo.io/t/<org_name>",
     scope: [ "openid","profile" ]
};

export const MyApp = (): ReactElement => {
    return (
        <AuthProvider config={ config }>
            <App />
        </AuthProvider>
    )
}

Note You can refer to the details of AuthProvider config here

Once the root component is wrapped with AuthProvider, useAuthContext() hook can be used anywhere within the application to implement user authentication capabilities in the application.

Using APIs

Best practices when using APIs

Asgardeo Auth React SDK is built on top of Asgardeo Auth SPA SDK, a base library. Hence, almost all the usable APIs from Auth SPA SDK are re-exported from Asgardeo Auth React SDK and you don't need to import dependencies from the base library to your application.

  • The only SDK that should be listed in the app dependencies is @asgardeo/auth-react.
  • Always import APIs from @asgardeo/auth-react.

Warning IDE or Editor auto import may sometimes import certain APIs from @asgardeo/auth-spa, change them back manually.

DO ✅

import { AsgardeoSPAClient } from "@asgardeo/auth-react";

When including React SDK as a dependency:

DO ✅
// In package.json

dependencies: {
    "@asgardeo/auth-react": "^2.0.0"
}

useAuthContext() hook

The useAuthContext() hook provided by the SDK could be used to implement the necessary authentication functionalities and access the session state that contains information such as a unique identifier for the authenticated user.

Import the useAuthContext() hook from @asgardeo/auth-react.

import { useAuthContext } from "@asgardeo/auth-react";

And then inside your components, you can access the context as follows

const { state, signIn, signOut } = useAuthContext();

Few common methods that you will require when implementing authentication capabilities in your application.

  • signIn - Initiate a login request to Asgardeo, process the response to obtain authentication response.
  • signOut - Logout the user from Asgardeo and clear any authentication data from the SDK storage.
  • isAuthenticated - Check whether there is an authenticated user session. Based on the result you can decide to change the application view/behaviour.
  • getBasicUserInfo - Get authenticated user's basic information from the authentication response.
  • getDecodedIDToken - Get the decoded id_token obtained in the authentication response. From there you can derive more information such as additional user-attributes.
  • getIDToken - Get the id_token (JWT) obtained in the authentication response.
  • getAccessToken - Get the access_token obtained in the authentication response.
  • refreshAccessToken - Get the refresh_token obtained in the authentication response.
  • getHttpClient - Get an HttpClient instance so that the you can make RESTful calls to the backend, where the client will attach the necessary Authorization headers to the request.

The state object will contain attributes such as whether a user is currently logged in, the username of the currently logged-in user etc.

Note You can refer to the detailed API documentation here


Add a Login/Logout Button

You can use the signIn() method from useAuthContext() to easily implement a login button.

<button onClick={ () => signIn() }>Login</button>

Similarly to the above step, we can use the signOut() method from useAuthContext() to implement a logout button.

<button onClick={() => signOut()}>Logout</button>

Clicking on Login button will take the user to Asgardeo login page. Upon successful signIn(), the user will be redirected to the app (based on the specified signInRedirectURL) and the state.isAuthenticated will be set to true.

Clicking on Logout button will sign out the user and will be redirected to signOutRedirectURL and the state.isAuthenticated will be set to false.

Note Instead of buttons you can use the signIn() & signOut() methods from the SDK to implement any preffered user-experience in your application

You can use the state.isAuthenticated attribute to check the authenticated status of the user.


Show Authenticated User's Information

The following code snippet demonstrates the usage of the state object, together with signIn() and signOut() methods from the context.

import React from "react";
import { useAuthContext } from "@asgardeo/auth-react";

function App() {

  const { state, signIn, signOut } = useAuthContext();

  return (
    <div className="App">
      {
        state.isAuthenticated
          ? (
            <div>
              <ul>
                <li>{state.username}</li>
              </ul>

              <button onClick={() => signOut()}>Logout</button>
            </div>
          )
          : <button onClick={() => signIn()}>Login</button>
      }
    </div>
  );
}

export default App;

Add Routing

If your application needs routing, the SDK provides a multiple approaches to secure routes in your application. You can read more about routing capabilities in Asgardeo here.


API Documentation

Additionally to above, Asgardeo offers a wide range of APIs that you can use to integrate and make use of Asgardeo within your React Application. You can refer to a detailed API documentation here.

Sample Apps

Sample React Apps offered by Asgardeo will allow you to take Asgardeo for a spin without having to setup your own application. You can see how to setup sample apps here.

Develop

Prerequisites

  • Node.js (version 10 or above).
  • yarn package manager.

Installing Dependencies

The repository is a mono repository. The SDK repository is found in the lib directory. You can install the dependencies by running the following command at the root.

yarn build

Contribute

Please read Contributing to the Code Base for details on our code of conduct, and the process for submitting pull requests to us.

Reporting issues

We encourage you to report issues, improvements, and feature requests creating Github Issues.

Important: And please be advised that security issues must be reported to security@wso2com, not as GitHub issues, in order to reach the proper audience. We strongly advise following the WSO2 Security Vulnerability Reporting Guidelines when reporting the security issues.

License

This project is licensed under the Apache License 2.0. See the LICENSE file for details.