Code Monkey home page Code Monkey logo

expo-keycloak's Introduction

npm

Keycloak for Expo

Keycloak authentication for react-native apps using Expo.

This package enables you to login against a keycloak instance from your Expo app without the need to eject!

This package also automatically handles refreshing of the token. (You can disable this behavior in KeycloakProvider props)

Install

1. Expo & React peer deps

Expo and React should already be in your project, but just in case, let's make it clear you need those. Better yet, Expo should be in version 40 or above.

2. Expo modules

To ensure maximum compatibility, we will install these separately:

expo install expo-random expo-auth-session

3. Other peer deps and the star of the evening expo-keycloak itself

yarn add @react-native-async-storage/async-storage expo-keycloak

Usage

// App.tsx
import {
  IKeycloakConfiguration,
  KeycloakProvider,
  useKeycloak,
} from 'expo-keycloak';
import AppConfig from './app.json'; // This is Expo's app json where your scheme should be defined

export default () => {
  const keycloakConfiguration: IKeycloakConfiguration = {
    clientId: 'AGENT_007',
    realm: 'REALM_OF_HER_MAJESTY',
    url: 'http://WHERE_THE_KC_RESIDES', // This is usually an url ending with /auth
    scheme: AppConfig.expo.scheme,
  };

  return (
    <KeycloakProvider {...keycloakConfiguration}>
      <Auth />
    </KeycloakProvider>
  );
};
// Auth.tsx
import { ActivityIndicator, Button, Text } from 'react-native';

export const Auth = () => {
  const {
    ready, // If the discovery is already fetched
    login, // The login function - opens the browser
    isLoggedIn, // Helper boolean to use e.g. in your components down the tree
    token, // Access token, if available
    logout, // Logs the user out
  } = useKeycloak();
  if (!ready) return <ActivityIndicator />;

  if (!isLoggedIn)
    return (
      <View style={{ margin: 24 }}>
        <Button onPress={login} title={'Login'} />
      </View>
    );

  return (
    <View style={{ margin: 24 }}>
      <Text style={{ fontSize: 17, marginBottom: 24 }}>Logged in!</Text>
      <Text>Token: {token.slice(0, 24)}...</Text>
      <Button onPress={logout} title={'Logout'} style={{ marginTop: 24 }} />
    </View>
  );
};

expo-keycloak's People

Contributors

balgamat avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

expo-keycloak's Issues

Keycloak doesn't reopen my app inside expo correctly

I have a problem where after I log in successfully through keycloak expo doesn't return me to my app. This only happen while I'm developing my app in expo, after doing a build it works perfectly. The error I get is: "Uncaught Error: java.net.SocketTimeoutException: failed to connect to /192.168.1.112 (port 80) from /192.168.1.62 (port 40504) after 10000ms." I'm 99% sure that the problem is the fact that it is trying to connect to port 80, however the development server runs on port 19000 (the default expo dev port).
Thank you in advance!

Cannot prompt to authenticate issue on Android devices

Hello,

I'm facing the below issue when run expo keycloak authentication on Android devices.

In IOS it's working fine, I'm able to open the prompt, insert the keycloak credentials and perform the login, but in Android I'm getting the below issue.

[Unhandled promise rejection: Error: Cannot prompt to authenticate until the request has finished loading.]

can not work

Invariant Violation: Calling synchronous methods on native modules is not supported in Chrome.

Consider providing alternative methods to expose this method in debug mode, e.g. by exposing constants ahead-of-time.

This error is located at:
in KeycloakProvider (at App.tsx:17)
in _default (created by ExpoRoot)
in ExpoRoot (at renderApplication.js:45)
in RCTView (at View.js:34)
in View (at AppContainer.js:106)
in DevAppContainer (at AppContainer.js:121)
in RCTView (at View.js:34)
in View (at AppContainer.js:132)
in AppContainer (at renderApplication.js:39)
at node_modules/expo/build/logs/LogSerialization.js:155:14 in _captureConsoleStackTrace
at node_modules/expo/build/logs/LogSerialization.js:41:26 in serializeLogDataAsync

  • ... 9 more stack frames from framework internals

Auto refresh doesn't work

Hi,

Thanks for your work, this library is really very useful. However there is a little problem. The autorefresh of the token does not work.

I did some investigation to solve the problem and I think I found it.

const handleTokenRefresh = useCallback(() => {
    if (!hydrated) return;
    if (!savedTokens && hydrated) { // <-- always null
      updateState(null);
      return;
    }
    if (TokenResponse.isTokenFresh(savedTokens!)) {
      updateState({ tokens: savedTokens });
    }
    if (!discovery)
      throw new Error('KC Not Initialized. - Discovery not ready.');
    AuthSession.refreshAsync(
      { refreshToken: savedTokens!.refreshToken, ...config },
      discovery!,
    )
      .catch(updateState)
      .then(updateState);
  }, [discovery, hydrated, savedTokens, updateState]);

savedToken here is alway null and I don't understand why. I first thought that the problem was related to the setTimeout callback. I tried to use a useRef but it doesn't solve the problem.

Does anyone have an idea? I am willing to do a PR if necessary.

(translated from French with an automatic translator)

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.