question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

How to determine whether the user is authenticated to implement protected routes in React?

See original GitHub issue

Library

  • msal@1.x.x or @azure/msal@1.x.x
  • @azure/msal-browser@2.x.x
  • @azure/msal-node@1.x.x
  • @azure/msal-react@1.x.x
  • @azure/msal-angular@0.x.x
  • @azure/msal-angular@1.x.x
  • @azure/msal-angular@2.x.x
  • @azure/msal-angularjs@1.x.x

Description

I have a React SPA in which I have been able to implement authentication. However I would like to protect some of the routes, and have tried implementing it using something like:

import React from "react";
import { Route, Redirect } from "react-router-dom";

const ProtectedRoute = ({ component: Component, ...rest }) => {
  function isAuthenticated () {
    //Need Help
  }

  return (
    <>
      <Route
        {...rest}
        render={(props) => {
          if (isAuthenticated()) {
            return <Component {...props} />;
          } else {
            return (
              <Redirect
                to={{
                  pathname: "/",
                  state: {
                    from: props.location,
                  },
                }}
              />
            );
          }
        }}
      />
    </>
  );
};

export default ProtectedRoute;

with App.jsx looking like:

import React from "react";
import { BrowserRouter as Router, Switch, Route } from "react-router-dom";

import Home from "./components/Home";
import Profile from "./components/Profile";
import ProtectedRoute from "./ProtectedRoute";

const App = () => {
  return (
    <Router>
      <Switch>
        <Route exact path="/" component={Home} />
        <ProtectedRoute exact path="/profile" component={Profile} />
      </Switch>
    </Router>
  );
};

export default App;

It seems that the pattern for implementing ProtectedRoute hinges on being able to implement isAuthenticated(), however this is where I am stuck. I tried using something like calling acquireTokenSilent but have not had success. The main motivation for trying to use ProtectedRoute was to avoid having to put <AuthenticatedTemplate> and <UnauthenticatedTemplate> in all my components. Is there some obvious method or pattern that I am missing? Thank you.

Source

Issue Analytics

  • State:closed
  • Created 3 years ago
  • Comments:6 (1 by maintainers)

github_iconTop GitHub Comments

1reaction
tnorlingcommented, Feb 10, 2021

@pjchungmd What you have here should work, let me know if you’re still facing any issues or if I can close this. The MsalAuthenticationTemplate is, admittedly, not very well documented at the moment besides being demonstrated in the samples so you can be forgiven for missing it. I will make sure this gets added to the docs soon.

0reactions
pjchungmdcommented, Feb 10, 2021

Thank you all for pointing me in the right direction. It was my fault for not realizing that MsalAuthenticationTemplate existed (should have figured there would be something like that). I also upgraded to 1.0.0-alpha.5. I still haven’t been fully able to implement protected routes, so I implemented a ProtectedPage component, which ultimately does the same thing. My implementation looks like:

import React from "react";

// Msal imports
import {
  MsalAuthenticationTemplate,
} from "@azure/msal-react";

import { InteractionType } from "@azure/msal-browser";
import { loginRequest } from "../authConfig";

import { Loading } from "../authentication-ui/Loading";
import { ErrorComponent } from "../authentication-ui/ErrorComponent";

const ProtectedPage = (props) => {
  const authRequest = {
    ...loginRequest,
  };

  return (
    <MsalAuthenticationTemplate
      interactionType={InteractionType.Redirect}
      authenticationRequest={authRequest}
      errorComponent={ErrorComponent}
      loadingComponent={Loading}
    >
      {props.children}
    </MsalAuthenticationTemplate>
  );
};

export default ProtectedPage;

Are there any glaring errors with doing it this way? Again many thanks for the help and feedback.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Protected Routes and Authentication with React Router - ui.dev
Protected routes let us choose which routes users can visit based on whether they are logged in. For example, you might have public...
Read more >
Implementing Protected Route and Authentication in React-JS
For this tutorial, I'll be showing how to set up an authentication route and protect other routes from been accessed by unauthorized users....
Read more >
Implement Authentication and Protect Routes in React
This is done by validating the identity of the person seeking access and then checking whether the person is authorized to enter or...
Read more >
React Router Tutorial - 15 - Authentication and Protected Routes
React Router Tutorial - 15 - Authentication and Protected Routes ; Courses - https://learn.codevolution.dev/ ; Support UPI - https://support ...
Read more >
React Router 6: Private Routes (alias Protected Routes)
Private Routes in React Router (also called Protected Routes) require a user being authorized to visit a route (read: page). So if a...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found