Git Product home page Git Product logo

loginradius-react's Introduction

loginradius-react

License npm

Table of Contents

Installation

Using npm

npm install loginradius-react

Getting Started

Configure the SDK by wrapping your application in LRAuthProvider:

// src/index.js
import React from "react";
import ReactDOM from "react-dom";
import App from "./App";
import { LRAuthProvider } from "loginradius-react";

ReactDOM.render(
  <React.StrictMode>
    <LRAuthProvider
      appName="YOUR_LOGINRADIUS_APPNAME"
      apiKey="YOUR_LOGINRADIUS_APIKEY"
      redirectUri={window.location.origin}
    >
      <App />
    </LRAuthProvider>
  </React.StrictMode>,
  document.getElementById("root")
);

Use the useLRAuth hook in your components to access authentication state (isLoading, isAuthenticated and user) and authentication methods (loginWithRedirect and logout):

// src/App.js
import React from "react";
import { useLRAuth } from "loginradius-react";

function App() {
  const { isLoading, isAuthenticated, error, user, loginWithRedirect, logout } =
    useLRAuth();

  if (isLoading) {
    return <div>Loading...</div>;
  }
  if (error) {
    return <div>Oops... {error.message}</div>;
  }

  if (isAuthenticated) {
    return (
      <div>
        Hello {user.name}{" "}
        <button onClick={() => logout({ returnTo: window.location.origin })}>
          Log out
        </button>
      </div>
    );
  } else {
    return <button onClick={() => loginWithRedirect()}>Log in</button>;
  }
}

export default App;

Protect a Route

Protect a route component using the withAuthenticationRequired higher order component. Visits to this route when unauthenticated will redirect the user to the login page and back to this page after login:

import React from "react";
import { withAuthenticationRequired } from "loginradius-react";

const PrivateRoute = () => <div>Private</div>;

export default withAuthenticationRequired(PrivateRoute, {
  // Show a message while the user waits to be redirected to the login page.
  onRedirecting: () => <div>Redirecting you to the login page...</div>,
});

Call an API

Call a protected API with an Access Token:

import React, { useEffect, useState } from "react";
import { useLRAuth } from "loginradius-react";

const CallAPI = () => {
  const { getAccessTokenSilently } = useLRAuth();
  const [resp setResp] = useState(null);

  useEffect(() => {
    (async () => {
      try {
        const token = await getAccessTokenSilently();
        const response = await fetch(
          `https://api.loginradius.com/identity/v2/auth/access_token/validate?access_token=${token}&apiKey=${process.env.REACT_APP_API_KEY}`,
          {}
        );
        setResp(await response.json());
      } catch (e) {
        console.error(e);
      }
    })();
  }, [getAccessTokenSilently]);

  if (!resp) {
    return <div>Loading...</div>;
  }

  return (
    <span>{JSON.stringify(state.apiMessage, null, 2)}</span>
  );
};

export default CallAPI;

Using loginWithPopup

To implement loginWithPopup functionality in your app you need to perform following steps:

  1. Open your LoginRadius Dashboard and navigate to Auth Page (IDX) -> Themes -> Customize -> Switch to Advance Editor.
  2. In the right side you will find the tab called Custom JS, expand and select Add New.
  3. A popup will open where you need to enter this url in the Url tab - https://hosted-pages.lrinternal.com/Themes/sdk/default-auth-react-sdk.js and click Confirm
  4. This URL contains the script which will help to close the popup after the authentication is done.
  5. Finally Click on Save and then add loginWithPopup method in your application.

Contributing

We appreciate feedback and contribution to this repo! Before you get started, please see the following:

Support + Feedback

For support or to provide feedback, please raise an issue on our issue tracker.

What is LoginRadius

  • LoginRadius was established with the vision of securing the identity of every person on the internet. Over a few short years, we have grown exponentially from a simple social login provider to a multi-faceted, industry-leading customer identity and access management (CIAM) platform.
  • The LoginRadius Identity Platform helps companies securely manage customer identities and data to deliver a unified customer experience. We offer suites of modules to serve businesses from startups to Fortune 500 enterprises with hundreds of millions of users.

License

This project is licensed under the MIT license. See the LICENSE file for more info.

loginradius-react's People

Contributors

drewf7 avatar mohammed786 avatar nefejames avatar

Stargazers

 avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

loginradius-react's Issues

Add Vue.js Example

We already have an examples folder where typescript-app and gatsby examples are already there, in a similar way we also need the Vue.js example which can demonstrate the implementation of LoginRadius React SDK in the Vue.js application.

Issue template

I would like to add an Issue template to the repo.
Let me know if that's needed.

Add Next.js Example

We already have an examples folder where typescript-app and gatsby examples are already there, in a similar way we also need the Next.js example which can demonstrate the implementation of LoginRadius React SDK in the Next.js application.

Add unit test for reducer

Hi @mohammed786, I was going through the code and found that we don't have UT added for reducer. Not sure if we want that but I feel that since reducers contain important business logic, they should be tested well on the type of state they are returning.

Let me know your thoughts on this. Would be really happy to help there ๐Ÿ™‚. Thanks!!

Next.js Auth Not Working

I can't seem to get your react SDK to work properly with Next.js. I'm able to log in, but not log out.

I passed in http://localhost:3000/ as a string directly where window.location.origin was used in the docs. I've whitelisted localhost in my dashboard. However, I can't log out.

<button onClick={() => logout({ returnTo: "http://localhost:3000/" })}>

When I try logging out, I'm told, "The host is not whitelisted. ", and it is whitelisted.

Please look into this.

Capture

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.