Giter Site home page Giter Site logo

react-openidconnect's Introduction

Simple React Wrapper around OIDC-Client.

Install

NPM

npm install --save react-openidconnect

Usage

Import the component and add <Authenticate> to you react app. All its children will be rendered when the user is authenticated. Otherwise a text is show asking the user to login, this text is provided as a prop.

The JWT is provided trough the callback 'userLoaded' and is called at them moment the user is retrieved from the identityserver. 'userUnLoaded' is called when the user is removed from session. Its up to you to decided what to do with the JWT.

Depending on the IdentityServer used, the JWT has an acces_token and an id_token which can be used to add to your Fecth request headers as bearer token. This will grant you access to the resource server.

Example

Assuming a Create-React app.

1 - Change your app.js file to

import React, { Component } from 'react';
import Authenticate from 'react-openidconnect';
import OidcSettings from './oidcsettings';
 
class App extends Component {
 
  constructor(props) {
    super(props);
    this.userLoaded = this.userLoaded.bind(this); 
    this.userUnLoaded = this.userUnLoaded.bind(this);
 
    this.state = { user: undefined };
  }  
 
  userLoaded(user) {
    if (user)
      this.setState({ "user": user });
  } 
  
  userUnLoaded() {
    this.setState({ "user": undefined });
  } 
 
  NotAuthenticated() {
    return <div>You are not authenticated, please click here to authenticate.</div>;
  }

  // @NOTE This function is optional. If you not pass it will looks for "#id_token" in the URL
  checkAuthentication() {
    return window.location.href.includes("my_token_hash"); 
  }
 
  render() {
      return (
        <Authenticate         
          OidcSettings={OidcSettings} 
          checkAuthentication={checkAuthentication}
          userLoaded={this.userLoaded} 
          userunLoaded={this.userUnLoaded} 
          renderNotAuthenticated={this.NotAuthenticated}
        >
            <div>If you see this you are authenticated.</div>
        </Authenticate>
      )
  }
}

export default App;

2 - Create a oidcsettings.js file in the same map as you app.js and provide the Oidc settings. You should retrieve these settings from you identity provider. Getting these settings right is normally the most frustrating part.

OidcSettings provides the following properties.

  • authority (string): The URL of the OIDC/OAuth2 provider.
  • client_id (string): Your client application’s identifier as registered with the OIDC/OAuth2 provider.
  • redirect_uri (string): The redirect URI of your client application to receive a response from the OIDC/OAuth2 provider.
  • scope (string): The scope being requested from the OIDC/OAuth2 provider (default: ‘openid’).
  • response_type: 'id_token token'.
  • post_logout_redirect_uri: (string): The redirect URI of your client after logout.

Example:

var OidcSettings = {    
    authority: 'https://****/identity',
    client_id: 'myclientid',
    redirect_uri: 'https://localhost:9090/',    
    response_type: 'id_token token',
    scope: 'openid profile roles',
    post_logout_redirect_uri: 'https://localhost:9090/'      
};

3 - You need to start your React app using the same url as in redirect_uri. The way to do this is to change the start script inside your package.json to.

windows
"start": "set PORT=9090&&set HTTPS=true&&react-scripts start" 

other
"start": "set PORT=9090 set HTTPS=true react-scripts start" (other)

NOTE: when authenticating against an identity provider, a redirect is used to provide the required token via the querystring. The <Authenticate> needs to pick-up this token so be sure the component is rendered when the redirect-url is called.

react-openidconnect's People

Contributors

bsvveen avatar rluders avatar

Stargazers

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

Watchers

 avatar  avatar

react-openidconnect's Issues

userLoaded not called

I'm using an identity OAUTH server that returns an access_token. is this why userLoaded is not getting called? If not, any ideas why this isn't called?

Objects are not valid as react child

i am currently using react with typescript. It currently works in all other browsers except for IE 11. It throws error as:
"Objects are not valid as a React child (found: object with keys {$$typeof, type, key, ref, props, _owner}). If you meant to render a collection of children, use an array instead." the code that i have is:

import React, { useState, useEffect } from "react";
import $ from "jquery";
import { default as OidcSettings } from "../../oidcsettings.json";
import { useDispatch, connect } from "react-redux";
import { getlogin } from "../../redux/login/action";
import { RootReducerState } from "../../redux/rootReducer";
import { loginState } from "../../redux/login/reducer";
import { useHistory } from "react-router-dom";

import Authenticate from "react-openidconnect";
// const Authenticate = require("react-openidconnect");

interface Props {
loginState: loginState;
}

const Login = ({ loginState }: Props) => {
const { isLoggedIn } = loginState;
const history = useHistory();
const [user, setUser] = useState(undefined);
const dispatch = useDispatch();

function userLoaded(user: any) {
if (user) setUser(user);
}

function userUnLoaded() {
setUser(undefined);
}

// @note This function is optional. If you not pass it will looks for "#id_token" in the URL
function checkAuthentication() {
return window.location.href.includes("code");
}

function NotAuthenticated() {
if (OidcSettings.autoLogin && !window.location.href.includes("code")) {
setTimeout(() => {
let ele = $("#btn");
ele.click();
});

  return <div id="btn"></div>;
} else if (
  OidcSettings.autoLogin &&
  window.location.href.includes("code")
) {
  return <div id="btn"></div>;
} else {
  return (
    <div className="banner">
      <div className="banner-content">
        <h3>
          Welcome to <img src="images/logo/ncell-logo.png" />
        </h3>
        <button id="btn" className="btn btn-primary">
          <i className="fa fa-sign-in"></i>Log in
        </button>
      </div>
    </div>
  );
}

}

useEffect(() => {
if (window.location.href.includes("code")) {
let code = window.location.href.split("=")[1].split("&")[0];

  login(code);
}

}, []);

function login(code: string) {
// evt.preventDefault();
// let { username, password } = this.state;
dispatch(getlogin("username", "password", code));
return false;
}

return (

If you see this you are authenticated.


);
};

const mapStateToProps = (state: RootReducerState) => {
return {
loginState: state.loginReducer,
};
};

export default connect(mapStateToProps)(Login);

can you think of any possible reason that why it is throwing error in IE only??

Opensource license

Hi- Please could you confirm under which Opensource license is this code available?

Thank you, Neha Sompura

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.