Git Product home page Git Product logo

ra-keycloak's Introduction

ra-keycloak

An auth provider for react-admin which handles authentication via a Keycloak server.

Documentationโ€‚ Source Codeโ€‚

This repository contains:

  • The actual ra-keycloak package
  • A simple demo app you can run locally to try out ra-keycloak

Simple Demo

Prerequesites

This demo requires Docker and docker-compose in order to start a local Keycloak server.

Initial setup

  1. Clone this project
  2. Run make install run to install the dependencies, start the local Keycloak Server and start the Demo App

We need to add some minimal configuration to our Keycloak server in order to use it. This need to be done from the Keycloak Admin Console.

  1. Browse to http://localhost:8080/ (note: keycloak takes some time to start...)
  2. Go to Administration Console
  3. Login with the default credentials (admin / password)
  4. Create a new Realm named for instance Marmelab
  5. Create a new Realm Role named admin
  6. Create a new Realm Role named user
  7. Create a new User named [email protected]
  8. For [email protected], under Credentials, set a new password (disable the temporary password tick)
  9. For [email protected], under Role mapping, click Assign role and choose admin
  10. Create a new User named [email protected]
  11. For [email protected], under Credentials, set a new password (disable the temporary password tick)
  12. For [email protected], under Role mapping, click Assign role and choose user
  13. Create a new Client and choose as Client ID front-marmelab. Leave all the other options to default.
  14. For Client front-marmelab, under Settings, edit the Access settings to the following:
  1. Click Save. Your keycloak instance is fully configured.

Using the Simple Demo

Now that all is configured and running, you can browse to http://localhost:8081/ to access the React Admin App.

  • Signing in with [email protected] will only grant the user role permissions
  • Signing in with [email protected] will grant full admin role permissions, allowing for instance to see the 'Users' resource in the main menu

Feel free to play around with this demo, along with the Keycloak config, to understand better how it works!

License

This repository and the code it contains is licensed under the MIT License and sponsored by marmelab.

ra-keycloak's People

Contributors

adguernier avatar arimet avatar fzaninotto avatar mchaffotte avatar slax57 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

ra-keycloak's Issues

Update example to use ref instead of state for keycloak existence check

The example provided causes an infinite redirect loop, similar to the the one described here and in many other instances with keycloak and the keycloak-js module.

In the example provided the keycloak existence check on this line causes an extra render in the app, which causes keycloak to redirect infinitely.

I resolved this by creating a new ref called 'didInit' (default value of false), which i set to true alongside keycloak init. Checking for the existence of this ref instead of the 'keycloak' state-stored variable resolves the extra render, which allows keycloak to work smoothly.

If there is a preferred workaround please let me know, otherwise I advise updating the example to use a ref as I described.

Error /protocol/openid-connect/token 401 (Unauthorized)

Hi i got error when trying authenticated and I am stuck at /protocol/openid-connect/token 401 (Unauthorized) after login on keycloack.

I try using keycloak server with auth.js by with next.js and it works.

 Keycloak server version 21.0.2

"keycloak-js": "^21.0.2",
"ra-keycloak": "^1.0.0",
"react": "^18.2.0",

Error occure in

keycloack.mjs

on line 762

req.onreadystatechange = function() {
     if (req.readyState == 4) {
          if (req.status == 200) {
               var tokenResponse = JSON.parse(req.responseText);
                   authSuccess(tokenResponse['access_token'], tokenResponse['refresh_token'], tokenResponse['id_token'], kc.flow === 'standard');
                        scheduleCheckIframe();
                    } else {
                        kc.onAuthError && kc.onAuthError();
                        promise && promise.setError();
                    }
                }
            };

            req.send(params);

App.tsx

const config: KeycloakConfig = {
  url: "http://localhost:8080",
  realm: "test-realm",
  clientId: "test-client",
};

const initOptions: KeycloakInitOptions = {
  onLoad: "login-required",
};

const getPermissions = (decoded: KeycloakTokenParsed) => {
  const roles = decoded?.realm_access?.roles;
  if (!roles) {
    return false;
  }
  if (roles.includes("admin")) return "admin";
  if (roles.includes("user")) return "user";
  return false;
};

const App = () => {
  const [keycloak, setKeycloak] = useState<Keycloak | undefined>(undefined);
  const authProvider = useRef<AuthProvider | undefined>(undefined);
  const dataProvider = useRef<DataProvider | undefined>(undefined);

  useEffect(() => {
    const initKeyCloakClient = async () => {
      const keycloakClient = new Keycloak(config);
      keycloakClient.clientSecret = "tPW4yfVEOurE.....";

      await keycloakClient.init(initOptions);

      authProvider.current = keycloakAuthProvider(keycloakClient, {
        onPermissions: getPermissions,
      });
      dataProvider.current = keyCloakTokenDataProviderBuilder(
        myDataProvider,
        keycloakClient
      );
      setKeycloak(keycloakClient);
    };
    if (!keycloak) {
      initKeyCloakClient();
    }
  }, [keycloak]);

  // hide the admin until the dataProvider and authProvider are ready
  if (!keycloak) return <p>Loading...</p>;

  return (
    <Admin
      authProvider={authProvider.current}
...

Access Settings
image

Capability Settings
image

Credentials Settings
image

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.