GithubHelp home page GithubHelp logo

darylbuckle / react-oauth2-authcode-provider Goto Github PK

View Code? Open in Web Editor NEW
0.0 1.0 1.0 5.63 MB

A npm package for authenticating with OAuth2 Authorisation Code Flow in React SPAs.

Home Page: https://darylbuckle.github.io/react-oauth2-authcode-provider

HTML 1.75% TypeScript 95.04% CSS 3.21%

react-oauth2-authcode-provider's Introduction

react-oauth2-authcode-provider

A component that can wrap react single page applications to implement authentication with OAuth2 Authorization Code Flow.

NPM JavaScript Style Guide

Contents


About

Wrap a single page react application with the AuthCodeProvider component to easily handle authentication with an OAuth2 server using Authorization Code flow for all pages, using just a few lines of code.

AuthCodeProvider can also be added to individual pages or react components to only require authentication for particular areas of an application.

A set of functions included in AuthCodeFunctions can also be used to initiate flows, get tokens, or sign requests.

Also includes Refresh token flow, and token management and logout flow.

Install

npm install --save react-oauth2-authcode-provider

Peer Dependencies;

  • React v16 +
  • Axios v0.19 +

Usage

Minimum required;

import React, { Component } from 'react'

import { AuthCodeProvider } from 'react-oauth2-authcode-provider'
import 'react-oauth2-authcode-provider/dist/index.css'

class Example extends Component {
  render() {
    return 
      <AuthCodeProvider 
        authenticationProps={{
          authUrl: 'https://yourauthserver.com/authorize',
          callBackPath: '/callbackpath',
          tokenUrl: 'https://yourauthserver.com/token',
          clientId: 'your_client_id',
          clientSecret: 'your_client_secret',
          scope: 'somescope offline_access'
        }}
      >
        <div>Your app will go here</div>
      </AuthCodeProvider>
  }
}

See the Examples for an application of this component. This showcases a few different use cases all in one single page application, and you can see this in action whilst hooked up to a test Auth0 server.

Build the Examples with npm install and then npm start to start the development server at http://localhost:3000.

Or view the online example at https://darylbuckle.github.io/react-oauth2-authcode-provider.

A simple example that always requires authentication can also be found at https://github.com/darylbuckle/react-oauth2-authcode-provider-test.

Props

AuthCodeProvider properties
Property Type Default Mandatory Description
authenticationProps AuthCodeProps true An instance of the AuthCodeAuthentication class. This contains properties needed to for the authentication flow.
authenticationRequired bool true false A prop used to toggle whether authentication is required. If false children will be rendered. If true, children will only be rendered when authenticated. Changing from false to true can be used to start the authentication flow.
doLogout bool false false A prop used to begin the logout flow. Changing from false to true can be used to start the logout flow.
returnTo string current path false Once a token has been retrieved this is the path to redirect back to. If not set it will redirect back to the current path.
history ReactRouterHistory false React router history object. If set this will be used for post authentication redirects and removing the code parameter. If not provided the page will be reloaded to remove the code parameter and redirect.
storagePrefix string '' false Used if you are authenticating with multiple oauth2 servers, you can store multiple access tokens. The second/third/etc instance should have a unique prefixes.
cookiePath string '/' false Determines the Path for cookies. If hosting in a subdirectory you should set this to the subdirectory path (/subdriectory).
onGetAuthCode func false A call back function that is called before being redirecting to the authorization endpoint.
onReceiveAuthCode func false A call back function that is called when redirected back to the application with the Code parameter populated.
onTokenObtained func false A call back function that is called after retrieving an access token.
onTokenObtainedError func false A call back function that is called if there is an error retrieving an access token.
onTokenRefreshed func false A call back function that is called after retrieving an access token from a refresh token in the background.
onTokenRefreshedError func false A call back function that is called if there is an error retrieving access token from a refresh token in the background.
enableDebugLog bool false false Set to true to allow additional logging to the console.
signInText string 'Signing you in' false The label 'Signing you in'
signInText string 'Signing you out' false The label 'Signing you out'
signInText string 'Sorry, we were unable to sign you in. Please try again later.' false The label 'Sorry, we were unable to sign you in. Please try again later.'
signInText string 'Your session has expired.\nSign in again to continue.' false The label 'Your session has expired.\nSign in again to continue.'
loaderComponent JSX.Element false You can use this prop to override the Loader with your own component. The component must support the props: text.
signInErrorComponent JSX.Element false You can use this prop to override the Sign in error message with your own component. The component must support the props: text, btnText, onBtnClick.

AuthCodeProps properties
Property Type Default Mandatory Description
authUrl string true Url of the authentication endpoint of the authentication server (login screen)
callBackPath string '' false Local path to redirect back to after authenticating
tokenUrl string true Url of the token endpoint of the authentication server
logoutUrl string false Url of the logout endpoint of the authentication server
logoutCallBackPath string false Local path to redirect back to after logging out
clientId string true Your applications Client Id
clientSecret string false Your applications Client Secret if applicable
scope string '' false Scope to request
usePkce boolean true false Enable proof key for code exchange (security)
useState boolean true false Enable state matching (security)
useNonce boolean true false Enable nonce matching (security)

Functions

The following functions can be imported from AuthCodeFunctions.

Function Returns Description
isLoggedIn boolean Returns true if there is a an access_token or refresh_token cookie present (IE. authorization has been completed)
hasTokenExpired boolean Determines if the current access_token is still valid (2 minute leeway)
hasAccessToken boolean Returns true if there is an access token cookie present
accessToken string Returns the access_token which is saved as a cookie
hasRefreshToken boolean Returns true if there is a refresh token cookie present
refreshToken string Returns the refresh_token which is saved as a cookie
signRequest object Adds Authorization = 'Bearer access_token' to request headers if an access_token is present
doAuthorizationCodeFlow void Begins authorization by redirecting to the authorization endpoint of the authentication server
doLogoutFlow void Begins logout by redirecting to the logout endpoint of the authentication server
base64URLEncode string base64 encodes a url
sha256 string sha256 encodes a string
getURIParameterByName string Gets the value of a uri parameter
parseJwt string Decode Jwt to json string

License

MIT © DarylBuckle 2020

react-oauth2-authcode-provider's People

Contributors

darylbuckle avatar dependabot[bot] avatar

Watchers

 avatar

Forkers

arudrakalyan

react-oauth2-authcode-provider's Issues

react-scripts 5.0 error

if I used the latest react-scripts, under errors are happened.

Compiled with problems:X

ERROR in ./node_modules/react-oauth2-authcode-provider/dist/index.modern.js 32:13-30

Module not found: Error: Can't resolve 'crypto' in '/node_modules/react-oauth2-authcode-provider/dist'

BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default.
This is no longer the case. Verify if you need this module and configure a polyfill for it.

If you want to include a polyfill, you need to:
	- add a fallback 'resolve.fallback: { "crypto": require.resolve("crypto-browserify") }'
	- install 'crypto-browserify'
If you don't want to include a polyfill, you can use an empty module like this:
	resolve.fallback: { "crypto": false }

Security issue

The clientSecret parameter should never be used on the front-end.
Exposing the clientSecret inside the front end application at any time makes your application vulnerable to attack.

Please use a back-end/proxy to handle the clientSecret.

Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in the componentWillUnmount method.

Given the following code:

i```
mport React from 'react'
import {AuthCodeProvider, AuthCodeFunctions} from 'react-oauth2-authcode-provider'
//import 'react-oauth2-authcode-provider/dist/index.css'

class Login extends React.Component {
constructor() {
super()

    this.tokenObtained = this.tokenObtained.bind(this)
    this.authenticationProps = {
        usePkce: false,
        authUrl: process.env.REACT_APP_AUTHORIZE_URL,
        tokenUrl: process.env.REACT_APP_ACCESS_TOKEN_URL,
        clientId: process.env.REACT_APP_CLIENT_ID,
        clientSecret: process.env.REACT_APP_CLIENT_SECRET,
        scope: ''
    }

    this.state = {
        tokenObject: null
    }
}

tokenObtained(token) {
    this.setState({tokenObject: token})
}

tokenAuth(token) {
    console.log('auth')
    console.log(token)
}

tokenRef(token) {
    console.log('ref')
    console.log(token)
}

tokenRec(token) {
    console.log('rec')
    console.log(token)
}

tokenError(error) {
    console.error(error)
}

render() {
    return (
        <AuthCodeProvider
            history={this.props.history}
            enableDebugLog={true}
            authenticationRequired={false}
            onReceiveAuthCode={(data) => this.tokenRec(data)}
            onTokenObtained={(data) => this.tokenObtained(data)}
            onGetAuthCode={(data) => this.tokenAuth(data)}
            onTokenRefreshed={(data) => this.tokenRef(data)}
            authenticationProps={this.authenticationProps}
      >
          <div>
            <p>You’ll now need to connect to Hoopla to grant Microsoft Teams access to your Hoopla data.</p>
            <button onClick={() => AuthCodeFunctions.doAuthorizationCodeFlow(this.authenticationProps)}>Connect To Hoopla</button>
          </div>
      </AuthCodeProvider>
    )
}

}

export default Login;


I receive `Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in the componentWillUnmount method.` in `tokenObtained`. 

storagePrefix not working when useState = true

FYI - using storagePrefix is not working when useState = true.

It looks like the doAuthorizationCodeFlow processing in AuthCodeFunctions.tsx is not propagating the storagePrefix value in the getCodeLocation call so the state is being saved without the storagePrefix. This causes a 'State does not match' error in tradeCodeForToken in AuthCodeProvider.tsx since it's looking for the value with the storagePrefix.

Let me know if you need more details.

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.