Installations
npm install redux-auth
Developer Guide
Typescript
No
Module System
CommonJS
Min. Node Version
>=0.10.32
Node Version
6.2.1
NPM Version
3.9.3
Score
54
Supply Chain
55.8
Quality
76.4
Maintenance
50
Vulnerability
97.1
License
Releases
Unable to fetch releases
Contributors
Unable to fetch Contributors
Languages
JavaScript (99.89%)
CSS (0.11%)
Developer
lynndylanhurley
Download Statistics
Total Downloads
105,460
Last Day
3
Last Week
26
Last Month
111
Last Year
10,378
GitHub Statistics
2,122 Stars
249 Commits
258 Forks
45 Watching
1 Branches
16 Contributors
Bundle Size
125.29 kB
Minified
29.76 kB
Minified + Gzipped
Package Meta Information
Latest Version
0.0.5-beta5
Package Id
redux-auth@0.0.5-beta5
Size
62.07 kB
NPM Version
3.9.3
Node Version
6.2.1
Total Downloads
Cumulative downloads
Total Downloads
105,460
Last day
0%
3
Compared to previous day
Last week
85.7%
26
Compared to previous week
Last month
16.8%
111
Compared to previous month
Last year
135.4%
10,378
Compared to previous year
Daily Downloads
Weekly Downloads
Monthly Downloads
Yearly Downloads
Dependencies
11
Peer Dependencies
1
Dev Dependencies
66
Simple, secure authentication for react + redux
TL;DR - View the Live Demo
You can see a complete working example here. The code for the demo is here.
Click this button to deploy the demo app to your own server:
--
Features:
- Supports isomorphic / universal / server-side rendering
- OAuth2 authentication components
- Email authentication components, including:
- Seamless integration with the devise token auth Rails gem.
- Includes the following themes:
- Material UI
- React Bootstrap
- A plain theme that you can style from scratch
- Support for multiple user types
- coming soon React Native support
- coming soon I18n support
- coming soon Can be configured to work with any API
This project comes bundled with a test app. You can run the demo locally by following these instructions, or you can use it here in production.
The demo uses React, and the source can be found here.
--
Table of Contents
- About this plugin
- Installation
- Components
- Methods
- Configuration
- Using Multiple User Types
- API Expectations
- Contributing
- Development
- Callouts
About this plugin
This plugin relies on token based authentication. This requires coordination between the client and the server. Diagrams are included to illustrate this relationship.
This plugin was designed to work out of the box with the wonderful devise token auth gem, but it's flexible enough to be used in just about any environment.
About security: read here for more information on securing your token auth system. The devise token auth gem has adequate security measures in place, and this plugin was built to work seamlessly with that gem.
--
Installation
Only npm is currently supported.
1npm install redux-auth --save
If you want to use the Material UI or Bootstrap themes, you will need to install those libraries as well.
1# install material ui 2npm install material-ui --save 3 4# or bootstrap 5npm install react-bootstrap --save
Material UI uses inline styles so no further configuration is needed. But with the bootstrap theme, the CSS will also need to be included. Read more at the React Bootstrap project page.
You must also install and use a json loader
--
Usage
Components
There are 3 Themes included in this module.
- Material UI
- Bootstrap
- A default theme
The default theme has no styling, and honestly it just looks really bad. But if you hate heavy UI frameworks and you like to style everything yourself, then you will love the default theme.
All components can make their own API requests, display errors, and display success messages out of the box.
The examples shown below use the Material UI theme.
--
EmailSignUpForm
A form used for email based registration.
EmailSignUpForm props:
endpoint
: The key of the target provider service as represented in the endpoint configuration block.inputProps
: An object containing the following attributes:email
: An object that will override the email input component's default props.password
: An object that will override the password input component's default props.passwordConfirmation
: An object that will override the password confirmation input component's default props.submit
: An object that will override the submit button component's default props.
EmailSignUpForm usage
1// default theme 2import { EmailSignUpForm } from "redux-auth"; 3 4// material ui theme 5import { EmailSignUpForm } from "redux-auth/material-ui-theme"; 6 7// bootstrap theme 8import { EmailSignUpForm } from "redux-auth/bootstrap-theme"; 9 10// render 11render: () { 12 return <EmailSignUpForm />; 13}
View EmailSignUpForm API Expectations
--
EmailSignInForm
A form used to sign in using accounts that were registered by email.
EmailSignInForm props:
endpoint
: The key of the target provider service as represented in the endpoint configuration block.next
: A method to call on successful sign-in.inputProps
: An object containing the following attributes:email
: An object that will override the email input component's default props.password
: An object that will override the password input component's default props.submit
: An object that will override the submit button component's default props.
1// default theme 2import { EmailSignInForm } from "redux-auth"; 3 4// material ui theme 5import { EmailSignInForm } from "redux-auth/material-ui-theme"; 6 7// bootstrap theme 8import { EmailSignInForm } from "redux-auth/bootstrap-theme"; 9 10// render 11render: () { 12 return <EmailSignInForm />; 13}
View EmailSignInForm API expectations
--
OAuthSignInButton
A button used to authenticate using an OAuth provider (facebook, github, etc.).
OAuthSignInButton props:
endpoint
: The key of the target provider service as represented in the endpoint configuration block.provider
: The name of the target provider service as represented in theauthProviderPaths
endpoint configuration.next
: A method to call on successful sign-in.
Any additional properties will be passed on the button component of the given theme.
1// default theme 2import { OAuthSignInButton } from "redux-auth"; 3 4// material ui theme 5import { OAuthSignInButton } from "redux-auth/material-ui-theme"; 6 7// bootstrap theme 8import { OAuthSignInButton } from "redux-auth/bootstrap-theme"; 9 10// render 11render: () { 12 // using the default label 13 return <OAuthSignInButton />; 14 15 // or using custom label text 16 return <OAuthSignInButton>Custom Label</OAuthSignInButton>; 17}
View OAuthSignInButton API expectations
--
SignOutButton
A button used to end the current user's session.
SignOutButton props:
endpoint
: The key of the target provider service as represented in the endpoint configuration block. If this property isn't provided, the current signed in user will be signed out regardless of their user type.next
: A method to call upon successful sign-out.
Any additional properties will be passed on the button component of the given theme.
1// default theme 2import { SignOutButton } from "redux-auth"; 3 4// material ui theme 5import { SignOutButton } from "redux-auth/material-ui-theme"; 6 7// bootstrap theme 8import { SignOutButton } from "redux-auth/bootstrap-theme"; 9 10// render 11render: () { 12 // using the default label 13 return <SignOutButton />; 14 15 // or using custom label text 16 return <SignOutButton>Custom Label</SignOutButton>; 17}
View SignOutButton API expectations
--
DestroyAccountButton
A button used to destroy the account of the current user. This will also end the destroyed user's session.
DestroyAccountButton props:
endpoint
: The key of the target provider service as represented in the endpoint configuration block. If this property isn't provided, the current signed in user's account will be destroyed regardless of their user type.
Any additional properties will be passed on the button component of the given theme.
1// default theme 2import { DestroyAccountButton } from "redux-auth"; 3 4// material ui theme 5import { DestroyAccountButton } from "redux-auth/material-ui-theme"; 6 7// bootstrap theme 8import { DestroyAccountButton } from "redux-auth/bootstrap-theme"; 9 10// render 11render: () { 12 // using the default label 13 return <DestroyAccountButton />; 14 15 // or using custom label text 16 return <DestroyAccountButton>Custom Label</DestroyAccountButton>; 17}
View DestroyAccountButton API Expectations
--
RequestPasswordResetForm
A form used to send password reset emails to users that forgot their password. When users click the link included in the email, they will be redirected to the site that the request was made from. A modal will appear that contains a form allowing the user to create a new password.
RequestPasswordResetForm props:
endpoint
: The key of the target provider service as represented in the endpoint configuration block.inputProps
: An object containing the following attributes:email
: An object that will override the email input component's default props.submit
: An object that will override the submit button component's default props.
1// default theme 2import { RequestPasswordResetForm } from "redux-auth"; 3 4// material ui theme 5import { RequestPasswordResetForm } from "redux-auth/material-ui-theme"; 6 7// bootstrap theme 8import { RequestPasswordResetForm } from "redux-auth/bootstrap-theme"; 9 10// render 11render: () { 12 return <RequestPassswordResetForm />; 13}
View RequestPasswordResetForm API Expectations
--
UpdatePasswordForm
A form that can be used to change the current user's password.
UpdatePasswordForm props:
endpoint
: The key of the target provider service as represented in the endpoint configuration block. If this value is not provided, the current user's password will be updated regardless of their user type.inputProps
: An object containing the following attributes:password
: An object that will override the password input component's default props.passwordConfirmation
: An object that will override the password confirmation input component's default props.submit
: An object that will override the submit button component's default props.
1// default theme 2import { UpdatePasswordForm } from "redux-auth"; 3 4// material ui theme 5import { UpdatePasswordForm } from "redux-auth/material-ui-theme"; 6 7// bootstrap theme 8import { UpdatePasswordForm } from "redux-auth/bootstrap-theme"; 9 10// render 11render: () { 12 return <UpdatePasswordForm />; 13}
View UpdatePasswordForm API Expectations
--
AuthGlobals
This component contains all of the modals used in authentication, and also the component that is used to pass credentials from the server to the client when using server side rendering.
This component MUST live at the top level of your application outside of your routes.
AuthGlobals example using redux-router
The following example shows the relevant router configuration. Note that this is not a complete example. See the demo app for a complete, working setup.
1// default theme 2import { AuthGlobals } from "redux-auth"; 3 4// material ui theme 5import { AuthGlobals } from "redux-auth/material-ui-theme"; 6 7// bootstrap theme 8import { AuthGlobals } from "redux-auth/bootstrap-theme"; 9 10// your main app component. notice that AuthGlobals lives at the same level 11// as the app's children. 12class App extends React.Component { 13 render() { 14 return ( 15 <div> 16 <AuthGlobals /> 17 {this.props.children} 18 </div> 19 ); 20 } 21} 22 23// example routes. the nested routes here will replace "this.props.children" 24// in the example above 25var routes = ( 26 <Route path="/" component={App}> 27 <IndexRoute component={Main} /> 28 <Route path="alt" component={Alt} /> 29 <Route path="login" component={SignIn} /> 30 <Route path="account" component={Account} onEnter={requireAuth} /> 31 </Route> 32);
--
Methods
configure
This must be run before your app is initialized. This should be run on both the server, and on the client. The server will need an additional argument containing information about the current request's cookies and location.
configure arguments
endpoints
: An object containing information about your API. This at least needs to contain the full path to your URL as theapiUrl
property. See here for a complete list of endpoint config options.settings
: When rendering serverside, this will need to be an object that contains the following attributes:isServer
: A boolean that must be set totrue
when rendering server-side.cookies
: A string representation of the cookies from the current request. This will be parsed for any auth credentials.location
: A string representation of the current request's URL.
Additionaly when rendering on client side some additional settings can be passed in settings
object.
cleanSession
: A boolean that tells if all locally stored credentials will be flushed.clientOnly
: A boolean that tells if code is run only on client side. Should be settrue
with only client-side usage.
--
configure example
1import { configure } from "redux-auth"; 2 3// server-side usage 4store.dispatch(configure( 5 {apiUrl: "https://api.graveflex.com"}, 6 {isServer: true, cookies, currentLocation} 7)).then(({redirectPath, blank} = {}) => { 8 // if `blank` is true, this is an OAuth redirect and should not 9 // be rendered 10 11 // use your server to render your app, or redirect 12 // to another location if the user is unauthorized. 13 14 // see the demo app for a more complete example. 15}); 16 17// client-side usage 18store.dispatch(configure( 19 {apiUrl: "https://api.graveflex.com"}, 20 {serverSideRendering: true, cleanSession: true} 21)).then(() => { 22 // your store should now have the current user. now render your 23 // app to the DOM. see the demo app for a more complete example. 24});
--
fetch
A wrapper around the whatwg fetch implementation that automatically sends and tracks authentication headers. See here for the complete spec.
Any requests to the API that rely on authentication will need to use the fetch
function included in this library.
--
fetch example
1import { fetch } from "redux-auth"; 2 3// usage 4fetch("http://api.mysite.com").then(resp => { 5 alert(`Api response: `${resp}`); 6});
--
Configuration
This is the most difficult step, but only because configuring a redux app is inherently difficult.
The following example assumes that you are familiar with redux, and that you know how to create a store. Also keep in mind that this is a really basic example that does not even include routing. See the demo app for a more complete example.
This example assumes a directory structure that looks like this:
src/
app.js
client.js
server.js
config shared by both client and server
1// app.js 2import React from "react"; 3import {Provider} from "react-redux"; 4import {configure, authStateReducer, AuthGlobals} from "redux-auth"; 5import {createStore, compose, applyMiddleware, combineReducers} from "redux"; 6import {AuthGlobals} from "redux-auth" 7 8class App extends React.Component { 9 render() { 10 return ( 11 <div> 12 <AuthGlobals /> 13 {this.props.children} 14 </div> 15 ); 16 } 17} 18 19// create your main reducer 20const reducer = combineReducers({ 21 auth: authStateReducer, 22 // ... add your own reducers here 23}); 24 25// create your app's store. 26// note that thunk is required to use redux-auth 27const store = compose( 28 applyMiddleware(thunk), 29 // ... add additional middleware here (router, etc.) 30)(createStore)(reducer); 31 32// a single function can be used for both client and server-side rendering. 33// when run from the server, this function will need to know the cookies and 34// url of the current request. also be sure to set `isServer` to true. 35export function renderApp({cookies, isServer, currentLocation} = {}) { 36 // configure redux-auth BEFORE rendering the page 37 store.dispatch(configure( 38 // use the FULL PATH to your API 39 {apiUrl: "http://api.catfancy.com"}, 40 {isServer, cookies, currentLocation} 41 )).then(({redirectPath, blank} = {}) => { 42 if (blank) { 43 // if `blank` is true, this is an OAuth redirect and should not 44 // be rendered 45 return <noscript />; 46 } else { 47 return ( 48 <Provider store={store} key="provider"> 49 <App /> 50 </Provider> 51 ); 52 } 53 }); 54}
server-side rendering configuration
1// server.js 2import qs from "query-string"; 3import {renderToString} from "react-dom/server"; 4import { renderApp } from "./app"; 5 6// render the main app component into an html page 7function getMarkup(appComponent) { 8 var markup = renderToString(appComponent) 9 10 return `<!doctype html> 11 <html> 12 <head> 13 <title>Redux Auth – Isomorphic Example</title> 14 </head> 15 <body> 16 <div id="react-root">${markup}</div> 17 <script src="/path/to/my/scripts.js"></script> 18 </body> 19 </html>`; 20} 21 22// this function will differ depending on the serverside framework that 23// you decide to use (express, hapi, etc.). The following example uses hapi 24server.ext("onPreResponse", (request, reply) => { 25 var query = qs.stringify(request.query); 26 var currentLocation = request.path + (query.length ? "?" + query : ""); 27 var cookies = request.headers.cookies; 28 29 renderApp({ 30 isServer: true, 31 cookies, 32 currentLocation 33 }).then(appComponent => { 34 reply(getMarkup(appComponent)); 35 }); 36}
client side rendering configuration
1// client.js 2import React from "react"; 3import ReactDOM from "react-dom"; 4import { renderApp } from "./app"; 5 6const reactRoot = window.document.getElementById("react-root"); 7renderApp().then(appComponent => { 8 ReactDOM.render(appComponent, reactRoot); 9});
Note: be sure to include the AuthGlobals
component at the top level of your application. This means outside of your Routes
if you're using something like react-router.
See below for the complete list of configuration options.
Multiple user types
This plugin allows for the use of multiple user authentication endpoint configurations. The following example assumes that the API supports two user classes, User
and EvilUser
. The following examples assume that User
authentication routes are mounted at /auth,
and the EvilUser
authentication routes are mounted at evil_user_auth
.
Multiple user type configuration
When using a single user type, you will pass a single object to the configure
method as shown in the following example.
1store.dispatch(configure({ 2 apiUrl: 'https://devise-token-auth.dev' 3}));
When using multiple user types, you will instead pass an array of configurations, as shown in the following example.
1store.dispatch(configure([ 2 { 3 default: { 4 apiUrl: 'https://devise-token-auth.dev' 5 } 6 }, { 7 evilUser: { 8 apiUrl: 'https://devise-token-auth.dev', 9 signOutUrl: '/evil_user_auth/sign_out', 10 emailSignInPath: '/evil_user_auth/sign_in', 11 emailRegistrationPath: '/evil_user_auth', 12 accountUpdatePath: '/evil_user_auth', 13 accountDeletePath: '/evil_user_auth', 14 passwordResetPath: '/evil_user_auth/password', 15 passwordUpdatePath: '/evil_user_auth/password', 16 tokenValidationPath: '/evil_user_auth/validate_token', 17 authProviderPaths: { 18 github: '/evil_user_auth/github', 19 facebook: '/evil_user_auth/facebook', 20 google: '/evil_user_auth/google_oauth2' 21 } 22 } 23 } 24], { 25 isServer, 26 cookies, 27 currentLocation 28));
Using multiple endpoints with redux-auth components
All components accept an endpoint
attribute that will determine which of the endpoint configurations the component should use. For forms that are used by non-authenticated users users (EmailSignInForm
, OAuthSignInButton
, etc.), the first configuration in the endpoint config will be used as the default if this value is not provided. For forms used by authenticated users (SignOutButton
, UpdatePassword
, etc.), the current user's endpoint will be used by default if this value is not provided.
The following example assumes a configuration where two endpoints have been defined, default
and auth
:
Component example:
1import { EmailSignInForm } from "redux-auth"; 2 3// within render method 4<EmailSignInForm endpoint="alt" />
--
Endpoint config options
This is the complete list of options that can be passed to the endpoint config.
1import { configure } from "redux-auth"; 2 3// ... configure store, routes, etc... // 4 5store.dispatch(configure({ 6 apiUrl: 'https://devise-token-auth.dev', 7 signOutPath: '/evil_user_auth/sign_out', 8 emailSignInPath: '/evil_user_auth/sign_in', 9 emailRegistrationPath: '/evil_user_auth', 10 accountUpdatePath: '/evil_user_auth', 11 accountDeletePath: '/evil_user_auth', 12 passwordResetPath: '/evil_user_auth/password', 13 passwordUpdatePath: '/evil_user_auth/password', 14 tokenValidationPath: '/evil_user_auth/validate_token', 15 authProviderPaths: { 16 github: '/evil_user_auth/github', 17 facebook: '/evil_user_auth/facebook', 18 google: '/evil_user_auth/google_oauth2' 19 } 20}).then(// ... render your app ... //
apiUrl
string
The base route to your api. Each of the following paths will be relative to this URL. Authentication headers will only be added to requests with this value as the base URL.
--
tokenValidationPath
string
Path (relative to apiUrl
) to validate authentication tokens. Read more.
--
signOutPath
string
Path (relative to apiUrl
) to de-authenticate the current user. This will destroy the user's token both server-side and client-side.
--
authProviderPaths
object
An object containing paths to auth endpoints. Keys should be the names of the providers, and the values should be the auth paths relative to the apiUrl
. Read more.
--
emailRegistrationPath
string
Path (relative to apiUrl
) for submitting new email registrations. Read more.
--
accountUpdatePath
string
Path (relative to apiUrl
) for submitting account update requests.
--
accountDeletePath
string
Path (relative to apiUrl
) for submitting account deletion requests.
--
emailSignInPath
string
Path (relative to apiUrl
) for signing in to an existing email account.
--
passwordResetPath
string
Path (relative to apiUrl
) for requesting password reset emails.
--
passwordUpdatePath
string
Path (relative to apiUrl
) for submitting new passwords for authenticated users.
--
Extended Documentation
Follow these links to learn more about what the API expects from this library, and to see diagrams on how it all fits together. All of this stuff happens automatically when using this library with the devise token auth gem, but this information will be useful if you need to implement your own API.
- Signing In With Email
- Signing In With OAuth
- Validating Returning Users
- Managing Session Tokens
- Signing Out
- Registering With Email
- Requesting Password Resets
- Destroying Accounts
- Updating Passwords
Contributing
- Create a feature branch with your changes.
- Write some test cases.
- Make all the tests pass.
- Issue a pull request.
I will grant you commit access if you send quality pull requests.
Development
Running the dev server
There is a test project in the demo
directory of this app. To start a dev server, perform the following steps.
cd
to the root of this project.cd dummy
npm install
npm run watch
A hot-reloading dev server will start on localhost:8000. The test suite will be run as well.
Running the tests
If you just want to run the tests, follow these steps:
cd
into the root of this projectnpm install
npm test
Testing against a live API
This plugin was built against this API. You can use this, or feel free to use your own.
Credits
Thanks to the following contributors:
- @transedward for letting me use the name
redux-auth
. - @bruz
Code and ideas were stolen from the following sources:
- this SO post on token-auth security
- this SO post on string templating
- this brilliant AngularJS module
License
WTFPL © Lynn Dylan Hurley
No vulnerabilities found.
Reason
no binaries found in the repo
Reason
license file detected
Details
- Info: project has a license file: LICENSE.md:0
- Info: FSF or OSI recognized license: Do What The F*ck You Want To Public License: LICENSE.md:0
Reason
0 existing vulnerabilities detected
Reason
0 commit(s) and 0 issue activity found in the last 90 days -- score normalized to 0
Reason
Found 2/28 approved changesets -- score normalized to 0
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
security policy file not detected
Details
- Warn: no security policy file detected
- Warn: no security file to analyze
- Warn: no security file to analyze
- Warn: no security file to analyze
Reason
project is not fuzzed
Details
- Warn: no fuzzer integrations found
Reason
branch protection not enabled on development/release branches
Details
- Warn: branch protection not enabled for branch 'master'
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
- Warn: 0 commits out of 4 are checked with a SAST tool
Score
3
/10
Last Scanned on 2025-01-27
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More