10
votes

Comment utiliser Auth0 avec react-admin?

J'essaie d'implémenter l'authentification en utilisant Auth0 dans une application react-admin v3. J'ai besoin d'implémenter un authProvider qui parle avec Auth0. Cela ressemble à quelque chose qui devrait être disponible quelque part, mais le plus proche que j'ai pu trouver était https://github.com/alexicum/merge-admin/blob/master/src/Auth/index.js , qui a environ 2 ans ( les SDK ont changé depuis).

Existe-t-il un authProvider Auth0 quelque part que je peux réutiliser ou dois-je l'implémenter moi-même?

Merci!


2 commentaires

Avez-vous eu de la chance avec ça? Je ne suis pas un développeur React et sur le point d'essayer la même chose et j'ai été plutôt surpris que votre question soit la chose la plus pertinente que j'ai pu trouver.


@Hastarin pas vraiment, j'ai dû en développer un moi-même. C'est encore assez hackish, et l'abstraction Auth0 et react-admin AuthProvider est fuyante à certains endroits. Cela fonctionne pour le moment, mais je cherche toujours une meilleure solution. Le meilleur jusqu'ici est github.com/alexicum/merge-admin/blob/master/src/Auth/index.j‌ s .


4 Réponses :


2
votes

Il est plus pratique d'encapsuler l'application react-admin avec une connexion native auth0, puis de fournir à react-admin dataProvider un client http qui lit le jeton jwt stocké dans le stockage local par auth0.


0 commentaires

5
votes

pour référence, voici un exemple d'un moyen d'intégrer react admin avec le package auth0-react

index.js

import { withAuth0, withAuthenticationRequired } from "@auth0/auth0-react";
import ApolloClient from "apollo-boost";

// I'm using Hasura w/ JWT Auth, so here's an example of how to set Authorization Header
async componentDidMount() {
    const token = await this.props.auth0.getAccessTokenSilently();

    const client = new ApolloClient({
      uri: "https://HASURA_URL/v1/graphql",
      headers: {
        Authorization: `Bearer ${token}`
      },
    });

    buildHasuraProvider({ client }).then((dataProvider) =>
      this.setState({ dataProvider })
    );
  }

export default withAuthenticationRequired(withAuth0(App));

App.js

import { Auth0Provider } from "@auth0/auth0-react";

ReactDOM.render(
  <Auth0Provider
    domain="XXXXX.auth0.com"
    clientId="XXXXX"
    audience="https://XXXXX"
    redirectUri={window.location.origin}
  >
    <React.StrictMode>
      <App />
    </React.StrictMode>
  </Auth0Provider>,
  document.getElementById("root")
);


1 commentaires

Bien que cela ne soit pas conforme à la manière avisée de react-admin de gérer l'auth, c'est certainement très simple et semble jusqu'à présent fiable. Merci!



0
votes

J'ai créé un exemple d'application avec Auth0 et la méthode d'authentification react-admin

https://github.com/spintech-software/react-admin-auth0-example

Voici le code du fournisseur d'authentification pour référence

import authConfig from "./authConfig";
import {Auth0Client} from '@auth0/auth0-spa-js';

const auth0 = new Auth0Client({
    domain: authConfig.domain,
    client_id: authConfig.clientID,
    cacheLocation: 'localstorage',
    useRefreshTokens: true
});

const CallbackURI = "http://localhost:3000/login"

export default {
    // called when the user attempts to log in
    login: (url) => {
        if (typeof url === 'undefined') {
            return auth0.loginWithRedirect({
                redirect_uri: CallbackURI
            })
        }
        return auth0.handleRedirectCallback(url.location);
    },
    // called when the user clicks on the logout button
    logout: () => {
        return auth0.isAuthenticated().then(function (isAuthenticated) {
            if (isAuthenticated) { // need to check for this as react-admin calls logout in case checkAuth failed
                return auth0.logout({
                    redirect_uri: window.location.origin,
                    federated: true // have to be enabled to invalidate refresh token
                });
            }
            return Promise.resolve()
        })
    },
    // called when the API returns an error
    checkError: ({status}) => {
        if (status === 401 || status === 403) {
            return Promise.reject();
        }
        return Promise.resolve();
    },
    // called when the user navigates to a new location, to check for authentication
    checkAuth: () => {
        return auth0.isAuthenticated().then(function (isAuthenticated) {
            if (isAuthenticated) {
                return Promise.resolve();
            }
            return auth0.getTokenSilently({
                redirect_uri: CallbackURI
            })
        })
    },
    // called when the user navigates to a new location, to check for permissions / roles
    getPermissions: () => {
        return Promise.resolve()
    },
};


0 commentaires

0
votes

Ma réponse suit l'approche authProvider -admin où j'utilise son authProvider comme ci-dessous. Il y a deux étapes principales:

  • Obtenez les données nécessaires à partir useAuth0 hook useAuth0 .
  • Convertissez authProvider en fonction où il prend les valeurs ci-dessus et renvoie un objet comme default.
// 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;
// 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>
    );
}

C'est ça.


0 commentaires