0.1.4 • Published 2 years ago

react-oauth2-authcode-provider v0.1.4

Weekly downloads
4
License
MIT
Repository
github
Last release
2 years ago

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;

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
PropertyTypeDefaultMandatoryDescription
authenticationPropsAuthCodePropstrueAn instance of the AuthCodeAuthentication class. This contains properties needed to for the authentication flow.
authenticationRequiredbooltruefalseA 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.
doLogoutboolfalsefalseA prop used to begin the logout flow. Changing from false to true can be used to start the logout flow.
returnTostringcurrent pathfalseOnce a token has been retrieved this is the path to redirect back to. If not set it will redirect back to the current path.
historyReactRouterHistoryfalseReact 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.
storagePrefixstring''falseUsed if you are authenticating with multiple oauth2 servers, you can store multiple access tokens. The second/third/etc instance should have a unique prefixes.
cookiePathstring'/'falseDetermines the Path for cookies. If hosting in a subdirectory you should set this to the subdirectory path (/subdriectory).
onGetAuthCodefuncfalseA call back function that is called before being redirecting to the authorization endpoint.
onReceiveAuthCodefuncfalseA call back function that is called when redirected back to the application with the Code parameter populated.
onTokenObtainedfuncfalseA call back function that is called after retrieving an access token.
onTokenObtainedErrorfuncfalseA call back function that is called if there is an error retrieving an access token.
onTokenRefreshedfuncfalseA call back function that is called after retrieving an access token from a refresh token in the background.
onTokenRefreshedErrorfuncfalseA call back function that is called if there is an error retrieving access token from a refresh token in the background.
enableDebugLogboolfalsefalseSet to true to allow additional logging to the console.
signInTextstring'Signing you in'falseThe label 'Signing you in'
signInTextstring'Signing you out'falseThe label 'Signing you out'
signInTextstring'Sorry, we were unable to sign you in. Please try again later.'falseThe label 'Sorry, we were unable to sign you in. Please try again later.'
signInTextstring'Your session has expired.\nSign in again to continue.'falseThe label 'Your session has expired.\nSign in again to continue.'
loaderComponentJSX.ElementfalseYou can use this prop to override the Loader with your own component. The component must support the props: text.
signInErrorComponentJSX.ElementfalseYou 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
PropertyTypeDefaultMandatoryDescription
authUrlstringtrueUrl of the authentication endpoint of the authentication server (login screen)
callBackPathstring''falseLocal path to redirect back to after authenticating
tokenUrlstringtrueUrl of the token endpoint of the authentication server
logoutUrlstringfalseUrl of the logout endpoint of the authentication server
logoutCallBackPathstringfalseLocal path to redirect back to after logging out
clientIdstringtrueYour applications Client Id
clientSecretstringfalseYour applications Client Secret if applicable
scopestring''falseScope to request
usePkcebooleantruefalseEnable proof key for code exchange (security)
useStatebooleantruefalseEnable state matching (security)
useNoncebooleantruefalseEnable nonce matching (security)

Functions

The following functions can be imported from AuthCodeFunctions.

FunctionReturnsDescription
isLoggedInbooleanReturns true if there is a an access_token or refresh_token cookie present (IE. authorization has been completed)
hasTokenExpiredbooleanDetermines if the current access_token is still valid (2 minute leeway)
hasAccessTokenbooleanReturns true if there is an access token cookie present
accessTokenstringReturns the access_token which is saved as a cookie
hasRefreshTokenbooleanReturns true if there is a refresh token cookie present
refreshTokenstringReturns the refresh_token which is saved as a cookie
signRequestobjectAdds Authorization = 'Bearer access_token' to request headers if an access_token is present
doAuthorizationCodeFlowvoidBegins authorization by redirecting to the authorization endpoint of the authentication server
doLogoutFlowvoidBegins logout by redirecting to the logout endpoint of the authentication server
base64URLEncodestringbase64 encodes a url
sha256stringsha256 encodes a string
getURIParameterByNamestringGets the value of a uri parameter
parseJwtstringDecode Jwt to json string

License

MIT © DarylBuckle 2020