Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Auth0 with react-admin?

I'm trying to implement authentication using Auth0 in a react-admin v3 app. I need to implement an authProvider that talks with Auth0. This sounds like something that should be available somewhere, but the closest I could find was https://github.com/alexicum/merge-admin/blob/master/src/Auth/index.js, which is about 2 years old (the SDKs have changed since then).

Is there an Auth0 authProvider somewhere I can reuse, or do I have to implement it myself?

Thanks!

like image 920
Vitor Baptista Avatar asked Jan 04 '20 13:01

Vitor Baptista


1 Answers

My answer is following react-admin approach where I use its authProvider like below. There are two main steps:

  • Get needed data from useAuth0 hook.
  • Convert authProvider into function where it takes the above values, and return an object like default.
// In App.js

import authProvider from './providers/authProvider';// my path is changed a bit

const App = () => {
  const {
    isAuthenticated,
    logout,
    loginWithRedirect,
    isLoading,
    error,
    user,
  } = useAuth0();
  const customAuthProvider = authProvider({
    isAuthenticated,
    loginWithRedirect,
    logout,
    user,
  });

  return (
      <Admin
        {...otherProps}
        authProvider={customAuthProvider}
      >
      {...children}
      </Admin>
    );
}
// My authProvider.js

const authProvider = ({
  isAuthenticated,
  loginWithRedirect,
  logout,
  user,
}) => ({
  login: loginWithRedirect,
  logout: () => logout({ returnTo: window.location.origin }),
  checkError: () => Promise.resolve(),
  checkAuth: () => (isAuthenticated ? Promise.resolve() : Promise.reject()),
  getPermissions: () => Promise.reject('Unknown method'),
  getIdentity: () =>
    Promise.resolve({
      id: user.id,
      fullName: user.name,
      avatar: user.picture,
    }),
});

export default authProvider;

That's it.

like image 134
ShinaBR2 Avatar answered Oct 02 '22 21:10

ShinaBR2