Skip to content

Instantly share code, notes, and snippets.

@fdidron
Last active April 11, 2023 13:54
Show Gist options
  • Star 70 You must be signed in to star a gist
  • Fork 27 You must be signed in to fork a gist
  • Save fdidron/ebcf52dc1ed62ff7d80725854d631a9e to your computer and use it in GitHub Desktop.
Save fdidron/ebcf52dc1ed62ff7d80725854d631a9e to your computer and use it in GitHub Desktop.
React Router v4 Auth
//Usage
import React from 'react';
import { BrowserRouter as Router } from 'react-router-dom';
import Route from './AuthRoute';
import Login from './Login';
import Private from './Private';
export default () =>
<Router>
<div>
<Route component={ Login } path="/login" />
<Route component={ Private } path="/private" />
</div>
</Router>;
import React from 'react';
import PropTypes from 'prop-types';
import { Redirect, Route } from 'react-router-dom';
//Mock of an Auth method, can be replaced with an async call to the backend. Must return true or false
const isAuthenticated = () => true;
const PRIVATE_ROOT = '/private';
const PUBLIC_ROOT = '/login';
const AuthRoute = ({component, ...props}) => {
const { isPrivate } = component;
if (isAuthenticated()) {
//User is Authenticated
if (isPrivate === true) {
//If the route is private the user may proceed.
return <Route { ...props } component={ component } />;
}
else {
//If the route is public, the user is redirected to the app's private root.
return <Redirect to={ PRIVATE_ROOT } />;
}
}
else {
//User is not Authenticated
if (isPrivate === true) {
//If the route is private the user is redirected to the app's public root.
return <Redirect to={ PUBLIC_ROOT } />;
}
else {
//If the route is public, the user may proceed.
return <Route { ...props } component={ component } />;
}
}
};
AuthRoute.propTypes = {
component: PropTypes.oneOfType([
PropTypes.element,
PropTypes.func
])
};
export default AuthRoute;
import React from 'react';
export default class Login extends React.Component {
static isPrivate = false
render() {
return <h1>{' Login '}</h1>;
}
}
import React from 'react';
export default class Private extends React.Component {
static isPrivate = true
render() {
return <h1>{' Private '}</h1>;
}
}
@stephenhandley
Copy link

i'm not clear on how you would replace this approach with an async call to backend

@sebelga
Copy link

sebelga commented Jun 18, 2017

First thanks for sharing this!
@stephenhandley You probably don't make an async call at all from the AuthRoute. The async should be done from a login form to authenticate and then save the session (cookie or JWT). The isAuthenticated() is then a sync call to check if there is a session.

I just followed this article http://www.thegreatcodeadventure.com/jwt-authentication-with-react-redux/ which works great with this. With that approach you can just pass the redux state "session" to the AuthRoute component and check if there session os true or false.

@chououtside
Copy link

This makes sense, but why is it that when I try and compile the code it webpack it throws an unexpected token error on the static is Private = true statements?

@IrvingArmenta
Copy link

I'm just learning about react and auth, but, I think propTypes should be loaded in a different way, according to the newer version of React:

import PropTypes from 'prop-types';

This should be the import.

@SeanJM
Copy link

SeanJM commented Jul 19, 2017

Thank you, this helped me, and I appreciate the effort of sharing this.

Here's my pretty printed version:

const IS_PUBLIC = [
  pages.login
];

const AuthRoute = ({component, ...props}) => {
  const { isPrivate } = component;

  if (isAuthenticated()) {
    //If route is private, user proceeds, else route is public, redirect use to private root.
    return isPrivate
      ? <Route { ...props } component={ component } />
      : <Redirect to={ PRIVATE_ROOT } />;
  } else {
    //If route is private, user is redirected to app's public root, else user proceeds.
    return isPrivate
      ? <Redirect to={ PUBLIC_ROOT } />
      : <Route { ...props } component={ component } />;
  }
};

@fdidron
Copy link
Author

fdidron commented Aug 3, 2017

Wow didn't realize you guys commented in there sorry for the late replies.

@stephenhandley Are you familiar with async / await ? isAuthenticated could be an async function making an HTTP call to your backend and based on the http response, return true or false. Then you would need to append await to any call to the isAuthenticated function.

@chououtside do you have Babel set to transpile ES7 ? Can you share your babelrc ?

@IrvingArmenta Totally correct, it wasn't the case when I published this. I will update the gist.

@SeanJM Thanks for sharing, your version is much more elegant

@pablodiablo93
Copy link

pablodiablo93 commented Aug 3, 2017

Thank you so much @fdidron, you saved my life from hours of struggling pain . Your solution is elegant and simple.

I have made some little changes to adapt it to my project, but i encountered a problem and i don't know how to face it.

I use create-react-app with redux and react-redux binding, and i managed the aync call in the login component, which work perfect and after the response i check all the data, then i return true or false and i dispatch an action to my store;

I use your component to 'Route' every component of my project and before i inserted redux in your AuthRoute and connected to the store
it worked perfectly, also in nested component.

The problem is that for an unknown reason when i start the project with npm start, after all the stuff have runned correctly, the shown url is 'localhost:3000/public/login', but the page is blank.

After an inspection with the react dev tool, i noticed that the render stops at the firt child of the AuthRoute, showing null on its child.
But... when i refresh the page, everything magically appears.

I apologize for this long question, but i'm a newbie in react and its world, and i cant' figure out what is the problem.

Here is my code:

import React from 'react';
import {Redirect, Route} from 'react-router-dom';
import PropTypes from 'prop-types';
import {connect} from 'react-redux'

const AuthRoute = ({component, ...props}) => {
    
    let isAuthenticated = props.authenticated;
    const PRIVATE_ROOT = '/private/';
    const PUBLIC_ROOT = '/public/login';
    
    const {isPrivate} = component;
    
    if (isAuthenticated) {
        //User is Authenticated
        if (isPrivate === true) {
            //If the route is private the user may proceed.
            return <Route {...props} component={component}/>;
        }
        else {
            //If the route is public, the user is redirected to the app's private root.
            return <Redirect to={PRIVATE_ROOT}/>;
        }
    }
    else {
        //User is not Authenticated
        if (isPrivate === true) {
            //If the route is private the user is redirected to the app's public root.
            return <Redirect to={PUBLIC_ROOT}/>;
        }
        else {
            //If the route is public, the user may proceed.
            return <Route {...props} component={component}/>;
        }
    }
};

const {element, func, bool} = PropTypes;

AuthRoute.propTypes = {
    component: PropTypes.oneOfType([
        element,
        func
    ]).isRequired,
    authenticated: PropTypes.bool
};

const mapStateToProps = (state) =>({
    authenticated : state.session.authenticated
});

export default connect(mapStateToProps)(AuthRoute)

@fdidron
Copy link
Author

fdidron commented Aug 5, 2017

@pablodiablo93 can you share your repo? I'll have a look at it.

@SeanJM
Copy link

SeanJM commented Aug 7, 2017

Another issue I have is this, when I register the routes:

<Route path="/login" component={pages.Login} />
<Route exact path="/test" component={pages.Test} />
<Route exact path="/test/list" component={pages.ListTest} />

As long as '/login' is present here, (when the user is logged in) it will always redirect the application to the private route.

--- More info ---
and there is another potential issue here, it's that "Redirect" is not a "Route" so it's a bit like the component is lying about it's nature.
I am continually rerouted the the private root when logged in.

@pablodiablo93
Copy link

Sorry @fdidron i was afk theese days, tomorrow i'll share my repo with you

@pablodiablo93
Copy link

Hi @fdidron.

As i promise, here my sample

https://github.com/pablodiablo93/my-example

@jamesattard
Copy link

This is a great workflow which I tested and works. However I cannot help but notice the console error:
bundle.js:22981 Warning: You tried to redirect to the same route you're currently on: "/login". This happens everytime I am not authenticated and get redirected to the 'public route'.

@TomOffringa
Copy link

Jep I'm having the same issue as @jamesattard. Probably because of the re-rendering and redirecting.

@quangas
Copy link

quangas commented Sep 24, 2017

@jamessattard @TomOffringa

I got the same warning but I found that if you wrap the routes around a Switch they disappeared.

<div>
<Switch>
[Route's go here]
</Switch>
</div>

@antonigiske
Copy link

I'm having the same issues as @TomOffringa and @jamesattard. Has anyone come up with a fix for this? It works, but the warnings annoy me, and must mean something isn't 100% alright.

@SCasarotto
Copy link

SCasarotto commented Sep 26, 2017

I am also seeing this issue, however, I am also using react-transition-group which may be exacerbating the issue. In my case, if I include a state value <Redirect to={{ pathname: '/signIn', state: { from: props.location } }}/> I actually get an infinite redirect loop that crashed on call stack size. I feel like what @antonigiske, @TomOffringa, @jamesattard and I are experiencing may be at the root of this.

EDIT 10/2/17: I thought of a simple way to fix what I was running into and thought if someone else has the same problem they might benefit from my solution. In my private route, I simply catch my '/signIn' route and return null. Stops the warning and infinite loop. I am sure there is a better way but it works for me for now.

@Snakeyyy
Copy link

Seems that @quangas <Switch> wrapper solves also the issue described by @pablodiablo93

@tcat
Copy link

tcat commented Oct 18, 2017

Just add exact to Redirect <Redirect exact from="/" to="/questions"/>

@brunow-smn
Copy link

@fdidron First of all, thank you! I'm really new to the React world and it helped me alot.
Now, i'm trying to implement the login page but, i dont know exactly how to redirect to the App page after submitting the form.

my submit handler code in Login.js:

handleSubmit(e) {
    e.preventDefault();
    const err = this.validate();

    const data = {
      username: this.state.username,
      password: this.state.password,
    };

    if (!err) {
      this.setState({
        username: '',
        usernameError: '',
        password: '',
        passwordError: '',
      });

      axios({
        method: 'post',
        url: 'http://localhost/Authenticate/api/Authentication',
        data: JSON.stringify(data),
        headers: {
          Accept: 'application/json',
          'content-type': 'application/json',
        },
      })
        .then((response) => {
          console.log(response);
          // tried to call a function to change isAuthenticated to true but doesnt redirect to /app page;
        })
        .catch((error) => {
          console.log(error);
          alert(error.response.data);
        });
    }
  }

I'm not using redux. Just trying to learn react by itself.

@thismarcoantonio
Copy link

thismarcoantonio commented Nov 14, 2017

@brunow-smn what response are you getting for the post request? Based in your response, I think you should change isAuthenticated (true or false) and then call the redirect function... I don't know too much, but that's it!

@brunow-smn
Copy link

@thismarcoantonio it just return a success status 200. Yes, but the problem(i think), just changing the value of isAuthenticated wont 're-mount' the component, because isAuthenticated is not a state. Maybe i need a if statement inside render() and have a stated variable like redirect.

Thanks for the reply!

@arr0nax
Copy link

arr0nax commented Dec 12, 2017

@SCasarotto I am also working with react-transition-group. I have the same thoughts as you! I will try your solution, or update if I come up with a more elegant one.

@bramchi
Copy link

bramchi commented Feb 25, 2018

@arr0nax @SCasarotto Could you share an example snippet of your solution? I'm having similar redirect issues since I added react-transition-group, but I'm not sure where and how to return that null route... Thanks! 😄

@SCasarotto
Copy link

@bramchi since this comment my <PrivateRoute/> has been updated a few times. Here is what I have been using in a number of production apps. It is possible it isn't the best practice but I haven't had problems with it so I haven't touched it in a while. Let me know if I can explain parts. Happy to help. 😄

Note: I use Firebase in most of my apps and so you will see that integrated here as well.

import React, { Component } from 'react'
import { connect } from 'react-redux'
import firebase from 'firebase'

//import PropTypes from 'prop-types'

import {
  Route,
  Redirect,
  withRouter
} from 'react-router-dom'

/**
 * Component that protects route from unauthorized users.
 * @type {Object}
 */
class PrivateRoute extends Component{
	render(){
		const { component: Component, requiredUserType, userPermissions, ...rest } = this.props
		//This catches the infinite loop and warning I was getting from the animation.
		if (rest.location.pathname === '/signIn'){ return null } 

		if (firebase.auth().currentUser){
			if (requiredUserType){
				if (userPermissions[requiredUserType]){
					return <Route {...rest} render={ props => <Component {...props}/> }/>
				}
				return <Route {...rest} render={ () => <Redirect to={{ pathname: '/portal/403' }} /> }/>
			}
			return <Route {...rest} render={ props => <Component {...props}/> }/>
		}
		return <Route {...rest} render={ props => <Redirect to={{ pathname: '/signIn', state: { from: props.location } }}/> }/>
	}
}

PrivateRoute.propTypes = {}

PrivateRoute.defaultProps = {}

const mapStateToProps = (state) => {
	const { userPermissions } = state.Auth
	return { userPermissions }
}

export default withRouter(connect(mapStateToProps)(PrivateRoute))

@AugustoPedraza
Copy link

If someone else get the error:

Warning: You tried to redirect to the same route you're currently on: "/login" react router
, here is the solution:

guyellis/learn#205 (comment)

@alsharmani1
Copy link

First thanks for sharing this!
@stephenhandley You probably don't make an async call at all from the AuthRoute. The async should be done from a login form to authenticate and then save the session (cookie or JWT). The isAuthenticated() is then a sync call to check if there is a session.

I just followed this article http://www.thegreatcodeadventure.com/jwt-authentication-with-react-redux/ which works great with this. With that approach you can just pass the redux state "session" to the AuthRoute component and check if there session os true or false.

What about checking if user is authorized if they leave the page and want to come back to it, like a simple refresh is going to remove store state. I am trying to achieve authentication while using httpOnly cookies so I have to make requests to my backend to authenticate the user. As far as I am concerned the only way I could do that is by making an async call, but I am assuming I might have to use something like a wrapper or an HOC to achieve this, any thoughts?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment