Przejdź do głównej zawartości

Sign users in to a React Native app

This guide explains how to run the Casdoor example for React Native and how to add Casdoor sign-in to your own app with casdoor-react-native-sdk.


Learning outcomes​

  • Run the example app on iOS and Android.
  • Install and initialize casdoor-react-native-sdk.
  • Sign a user in and read the user from the token.

What you need​

  • A React Native development environment, with an emulator or a connected device
  • An application in Casdoor

Sample code​


Run the example​

  1. Clone the example and install its dependencies:

    git clone git@github.com:casdoor/casdoor-react-native-example.git
    cd casdoor-react-native-example
    yarn install
    cd ios/ && pod install && cd ..
  2. Start an emulator or connect a device.

  3. Start the app.

    • On iOS: Run react-native start, and then react-native run-ios.
    • On Android: Run react-native start, and then react-native run-android.
    iOSAndroid
    iOS-loginAndroid-login
  4. Click Login with Casdoor. The Casdoor sign-in screen opens.

    iOSAndroid
    iOS-casdoor-loginAndroid-casdoor-login
  5. Sign in. The app shows the profile of the user.

    iOSAndroid
    iOS-userInfoAndroid-userInfo
iOSAndroid
iOS-gifAndroid-gif

Add sign-in to your app​

  1. Install the SDK:

    # NPM
    npm i casdoor-react-native-sdk

    # Yarn
    yarn add casdoor-react-native-sdk
  2. Initialize the SDK. The settings are strings.

    Name (in order)MustDescription
    serverUrlYesyour Casdoor server URL
    clientIdYesthe Client ID of your Casdoor application
    appNameYesthe name of your Casdoor application
    organizationNameYesthe name of the Casdoor organization connected with your Casdoor application
    redirectPathNothe path of the redirect URL for your Casdoor application, will be /callback if not provided
    signinPathNothe path of the signin URL for your Casdoor application
    import SDK from 'casdoor-react-native-sdk'

    const sdkConfig = {
    serverUrl: 'https://door.casdoor.com',
    clientId: 'b800a86702dd4d29ec4d',
    appName: 'app-example',
    organizationName: 'casbin',
    redirectPath: 'http://localhost:5000/callback',
    signinPath: '/api/signin',
    };
    const sdk = new SDK(sdkConfig)
  3. Call the SDK to sign the user in and to read the user:


    // get the signin url
    getSigninUrl()

    // get Access Token
    getAccessToken(redirectUrl); // http://localhost:5000/callback?code=b75bc5c5ac65ffa516e5&state=gjmfdgqf498

    // decode jwt token to get user info
    JwtDecode(jwtToken)

For the complete API, see the casdoor-react-native-sdk repository.

See also​