0

Follow up of this question: React Router Authorization

I understand the example provided here

https://github.com/ReactTraining/react-router/blob/master/examples/auth-flow/app.js

But I think this only answers the question of authentication and not authorization. Wheter the user is authenticated or not only depends on the presence of a value at the location there should be a jwt token in local storage.

 loggedIn() {
   return !!localStorage.token
 }

I know it will be impossible to do any server communication but what I'm after is completely hide my application behind a login. I don't see how I can achieve this in a SPA, should I split up my authentication and the rest of my application as 2 pages? What if I bring in roles?

Community
  • 1
  • 1
Jeremy Knees
  • 652
  • 1
  • 7
  • 21

1 Answers1

1

Simply pass the user role in to the component through props and perform a simple check to see if the user should be allowed to access this page. Redirect(possibly to a 404 page) otherwise.

const UserPage = ({userType}) => {    
    if(userType.role == 'user' || userType.role == 'admin') {
        return (
            <div>Basic Page Accessed</div>
        )
    } else {
        // Redirect
    }
}

const AdminPage = ({userType}) => {    
    if(userType.role == 'admin') {
        return (
            <div>Page Accessed</div>
        )
    } else {
        // Redirect
    }
}

Of course this isn't at all secure because everything occurs in the client side and there's nothing stopping a malicious/savvy user from firing off actions that they're not supposed to. That's why you also need to use authentication/authorisation on your backend too. So you can think of my example as more of a nice UI feature rather than an actual security feature. You could also use this library for front end authorisation but it seems like a bit much to me. The simple solution should do the trick.

The question then becomes one of authorisation/authentication of an API which is well answered here.

Of course this approach really only secures your data and not your actual application but I guess that's sufficient for most apps. If you really needs to block access to different pages completely then I guess React or some other SPA framework may not be the best for the project.

Community
  • 1
  • 1
John Devitt
  • 690
  • 2
  • 8
  • 22