Coder Social home page Coder Social logo

auth0 / react-native-auth0 Goto Github PK

View Code? Open in Web Editor NEW
472.0 16.0 201.0 6.71 MB

React Native toolkit for Auth0 API

Home Page: https://auth0.com

License: MIT License

JavaScript 43.11% Java 7.52% Objective-C 2.56% Ruby 1.26% Swift 3.97% TypeScript 41.04% C 0.04% Objective-C++ 0.52%
dx-sdk react-native

react-native-auth0's Introduction

react-native-auth0

Build Status NPM version Coverage License Downloads FOSSA Status

πŸ“š Documentation β€’ πŸš€ Getting Started β€’ ⏭️ Next Steps β€’ ❓ FAQs β€’ ❓ Feedback

⚠️ Important Migration Notice: v3.0.0

We're excited to announce the release of react-native-auth0 v3.0.0! Please note that this update includes breaking changes that require your attention. To ensure a smooth transition, please review our πŸ‘‰ Migration Guide πŸ‘ˆ for detailed instructions on updating your integration.

Documentation

Getting Started

Requirements

This SDK targets apps that are using React Native SDK version 0.60.5 and up. If you're using an older React Native version, see the compatibility matrix below.

Platform compatibility

The following shows platform minimums for running projects with this SDK:

Platform Minimum version
iOS 13.0
Android 28

Our SDK requires a minimum iOS deployment target of 13.0. In your project's ios/Podfile, ensure your platform target is set to 13.0.

platform :ios, '13.0'

Installation

First install the native library module:

With npm

$ npm install react-native-auth0 --save

With Yarn

$ yarn add react-native-auth0

Then, you need to run the following command to install the ios app pods with Cocoapods. That will auto-link the iOS library:

$ cd ios && pod install

Configure the SDK

You need to make your Android, iOS or Expo applications aware that an authentication result will be received from the browser. This SDK makes use of the Android's Package Name and its analogous iOS's Product Bundle Identifier to generate the redirect URL. Each platform has its own set of instructions.

Android

Before version 2.9.0, this SDK required you to add an intent filter to the Activity on which you're going to receive the authentication result, and to use the singleTask launchMode in that activity. To migrate your app to version 2.9.0+, remove both and continue with the instructions below. You can also check out a sample migration diff here.

Open your app's build.gradle file (typically at android/app/build.gradle) and add the following manifest placeholders:

android {
    defaultConfig {
        // Add the next line
        manifestPlaceholders = [auth0Domain: "YOUR_AUTH0_DOMAIN", auth0Scheme: "${applicationId}.auth0"]
    }
    ...
}

The auth0Domain value must be replaced with your Auth0 domain value. So if you have samples.us.auth0.com as your Auth0 domain you would have a configuration like the following:

android {
    defaultConfig {
        manifestPlaceholders = [auth0Domain: "samples.us.auth0.com", auth0Scheme: "${applicationId}.auth0"]
    }
    ...
}

The applicationId value will be auto-replaced at runtime with the package name or ID of your application (e.g. com.example.app). You can change this value from the build.gradle file. You can also check it at the top of your AndroidManifest.xml file.

Note that if your Android application is using product flavors, you might need to specify different manifest placeholders for each flavor.

If you use a value other than applicationId in auth0Scheme you will also need to pass it as the customScheme option parameter of the authorize and clearSession methods.

Take note of this value as you'll be requiring it to define the callback URLs below.

For more info please read the React Native docs.

Skipping the Web Authentication setup

If you don't plan to use Web Authentication, you will notice that the compiler will still prompt you to provide the manifestPlaceholders values, since the RedirectActivity included in this library will require them, and the Gradle tasks won't be able to run without them.

Re-declare the activity manually with tools:node="remove" in your app's Android Manifest in order to make the manifest merger remove it from the final manifest file. Additionally, one more unused activity can be removed from the final APK by using the same process. A complete snippet to achieve this is:

<activity
    android:name="com.auth0.android.provider.AuthenticationActivity"
    tools:node="remove"/>
<!-- Optional: Remove RedirectActivity -->
<activity
    android:name="com.auth0.android.provider.RedirectActivity"
    tools:node="remove"/>

iOS

Inside the ios folder find the file AppDelegate.[swift|m] add the following to it:

#import <React/RCTLinkingManager.h>

- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url
            options:(NSDictionary<UIApplicationOpenURLOptionsKey, id> *)options
{
  return [RCTLinkingManager application:app openURL:url options:options];
}

Inside the ios folder open the Info.plist and locate the value for CFBundleIdentifier, e.g.

<key>CFBundleIdentifier</key>
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>

and then below it register a URL type entry using the value of CFBundleIdentifier as the value for CFBundleURLSchemes:

<key>CFBundleURLTypes</key>
<array>
    <dict>
        <key>CFBundleTypeRole</key>
        <string>None</string>
        <key>CFBundleURLName</key>
        <string>auth0</string>
        <key>CFBundleURLSchemes</key>
        <array>
            <string>$(PRODUCT_BUNDLE_IDENTIFIER).auth0</string>
        </array>
    </dict>
</array>

If your application is generated using the React Native CLI, the default value of $(PRODUCT_BUNDLE_IDENTIFIER) matches org.reactjs.native.example.$(PRODUCT_NAME:rfc1034identifier). Take note of this value as you'll be requiring it to define the callback URLs below. If desired, you can change its value using XCode in the following way:

  • Open the ios/TestApp.xcodeproj file replacing 'TestApp' with the name of your app or run xed ios from a Terminal.
  • Open your project's or desired target's Build Settings tab and on the search bar at the right type "Product Bundle Identifier".
  • Replace the Product Bundle Identifier value with your desired application's bundle identifier name (e.g. com.example.app).
  • If you've changed the project wide settings, make sure the same were applied to each of the targets your app has.

If you use a value other than $(PRODUCT_BUNDLE_IDENTIFIER) in the CFBundleURLSchemes field of the Info.plist you will also need to pass it as the customScheme option parameter of the authorize and clearSession methods.

For more info please read the React Native docs.

Expo

⚠️ This SDK is not compatible with "Expo Go" app because of custom native code. It is compatible with Custom Dev Client and EAS builds

To use the SDK with Expo, configure the app at build time by providing the domain and the customScheme values through the Config Plugin. To do this, add the following snippet to app.json or app.config.js:

{
  "expo": {
    ...
    "plugins": [
      [
        "react-native-auth0",
        {
          "domain": "YOUR_AUTH0_DOMAIN",
          "customScheme": "YOUR_CUSTOM_SCHEME"
        }
      ]
    ]
  }
}
API Description
domain Mandatory: Provide the Auth0 domain that can be found at the Application Settings
customScheme Optional: Custom scheme to build the callback URL with. The value provided here should be passed to the customScheme option parameter of the authorize and clearSession methods. The custom scheme should be a unique, all lowercase value with no special characters.

Now you can run the application using expo run:android or expo run:ios.

Callback URL(s)

Callback URLs are the URLs that Auth0 invokes after the authentication process. Auth0 routes your application back to this URL and appends additional parameters to it, including a token. Since callback URLs can be manipulated, you will need to add this URL to your Application's Allowed Callback URLs for security. This will enable Auth0 to recognize these URLs as valid. If omitted, authentication will not be successful.

On the Android platform this URL is case-sensitive. Because of that, this SDK will auto convert the Bundle Identifier (iOS) and Application ID (Android) values to lowercase in order to build the Callback URL with them. If any of these values contains uppercase characters a warning message will be printed in the console. Make sure to check that the right Callback URL is whitelisted in the Auth0 dashboard or the browser will not route successfully back to your application.

Go to the Auth0 Dashboard, select your application and make sure that Allowed Callback URLs contains the URLs defined below.

If in addition you plan to use the log out method, you must also add these URLs to the Allowed Logout URLs.

Android

{YOUR_APP_PACKAGE_NAME}.auth0://{AUTH0_DOMAIN}/android/{YOUR_APP_PACKAGE_NAME}/callback

Make sure to replace {YOUR_APP_PACKAGE_NAME} and {AUTH0_DOMAIN} with the actual values for your application. The {YOUR_APP_PACKAGE_NAME} value provided should be all lower case.

iOS

{PRODUCT_BUNDLE_IDENTIFIER}.auth0://{AUTH0_DOMAIN}/ios/{PRODUCT_BUNDLE_IDENTIFIER}/callback

Make sure to replace {PRODUCT_BUNDLE_IDENTIFIER} and {AUTH0_DOMAIN} with the actual values for your application. The {PRODUCT_BUNDLE_IDENTIFIER} value provided should be all lower case.

Next Steps

This SDK is OIDC compliant. To ensure OIDC compliant responses from the Auth0 servers enable the OIDC Conformant switch in your Auth0 dashboard under Application / Settings / Advanced OAuth. For more information please check this documentation.

Web Authentication

The SDK exports a React hook as the primary interface for performing web authentication through the browser using Auth0 Universal Login.

Use the methods from the useAuth0 hook to implement login, logout, and to retrieve details about the authenticated user.

See the API Documentation for full details on the useAuth0 hook.

First, import the Auth0Provider component and wrap it around your application. Provide the domain and clientId values as given to you when setting up your Auth0 app in the dashboard:

import { Auth0Provider } from 'react-native-auth0';

const App = () => {
  return (
    <Auth0Provider domain="YOUR_AUTH0_DOMAIN" clientId="YOUR_AUTH0_CLIENT_ID">
      {/* YOUR APP */}
    </Auth0Provider>
  );
};

export default App;
Using the `Auth0` class

If you're not using React Hooks, you can simply instantiate the Auth0 class:

import Auth0 from 'react-native-auth0';

const auth0 = new Auth0({
  domain: 'YOUR_AUTH0_DOMAIN',
  clientId: 'YOUR_AUTH0_CLIENT_ID',
});

Then import the hook into a component where you want to get access to the properties and methods for integrating with Auth0:

import { useAuth0 } from 'react-native-auth0';

Login

Use the authorize method to redirect the user to the Auth0 Universal Login page for authentication. If scope is not specified, openid profile email is used by default.

  • The isLoading property is set to true once the authentication state of the user is known to the SDK.
  • The user property is populated with details about the authenticated user. If user is null, no user is currently authenticated.
  • The error property is populated if any error occurs.
const Component = () => {
  const { authorize, user, isLoading, error } = useAuth0();

  const login = async () => {
    await authorize();
  };

  if (isLoading) {
    return (
      <View>
        <Text>SDK is Loading</Text>
      </View>
    );
  }

  return (
    <View>
      {!user && <Button onPress={login} title="Log in" />}
      {user && <Text>Logged in as {user.name}</Text>}
      {error && <Text>{error.message}</Text>}
    </View>
  );
};
Using the `Auth0` class
auth0.webAuth
  .authorize()
  .then(credentials => console.log(credentials))
  .catch(error => console.log(error));

Web Authentication flows require a Browser application installed on the device. When no Browser is available, an error of type a0.browser_not_available will be raised via the provided callback.

SSO Alert Box (iOS)

ios-sso-alert

Check the FAQ for more information about the alert box that pops up by default when using Web Auth on iOS.

See also this blog post for a detailed overview of Single Sign-On (SSO) on iOS.

Logout

Log the user out by using the clearSession method from the useAuth0 hook.

const Component = () => {
  const { clearSession, user } = useAuth0();

  const logout = async () => {
    await clearSession();
  };

  return <View>{user && <Button onPress={logout} title="Log out" />}</View>;
};
Using the `Auth0` class
auth0.webAuth.clearSession().catch((error) => console.log(error));

Credentials Manager

The Credentials Manager allows you to securely store and retrieve the user's credentials. The credentials will be stored encrypted in Shared Preferences on Android, and in the Keychain on iOS.

The Auth0 class exposes the credentialsManager property for you to interact with using the API below.

πŸ’‘ If you're using Web Auth (authorize) through Hooks, you do not need to manually store the credentials after login and delete them after logout; the SDK does this automatically.

Check for stored credentials

When the users open your app, check for valid credentials. If they exist, you can retrieve them and redirect the users to the app's main flow without any additional login steps.

const isLoggedIn = await auth0.credentialsManager.hasValidCredentials();

if (isLoggedIn) {
  // Retrieve credentials and redirect to the main flow
} else {
  // Redirect to the login page
}

Retrieve stored credentials

The credentials will be automatically renewed using the refresh token, if the access token has expired. This method is thread safe.

const credentials = await auth0.credentialsManager.getCredentials();

πŸ’‘ You do not need to call credentialsManager.saveCredentials() afterward. The Credentials Manager automatically persists the renewed credentials.

Local authentication

You can enable an additional level of user authentication before retrieving credentials using the local authentication supported by the device, for example PIN or fingerprint on Android, and Face ID or Touch ID on iOS.

await auth0.credentialsManager.requireLocalAuthentication();

Check the API documentation to learn more about the available LocalAuthentication properties.

⚠️ You need a real device to test Local Authentication for iOS. Local Authentication is not available in simulators.

Credentials Manager errors

The Credentials Manager will only throw CredentialsManagerError exceptions. You can find more information in the details property of the exception.

try {
  const credentials = await auth0.credentialsManager.getCredentials();
} catch (error) {
  console.log(error);
}

Feedback

Contributing

We appreciate feedback and contribution to this repo! Before you get started, please see the following:

Raise an issue

To provide feedback or report a bug, please raise an issue on our issue tracker.

Vulnerability Reporting

Please do not report security vulnerabilities on the public Github issue tracker. The Responsible Disclosure Program details the procedure for disclosing security issues.


Auth0 Logo

Auth0 is an easy to implement, adaptable authentication and authorization platform. To learn more checkout Why Auth0?

This project is licensed under the MIT license. See the LICENSE file for more info.

react-native-auth0's People

Contributors

cocojoe avatar cranberyxl avatar damieng avatar dependabot[bot] avatar desusai7 avatar evansims avatar ewanharris avatar frederikprijck avatar hzalaz avatar jimmyjames avatar joshcanhelp avatar lanceharper avatar lbalmaceda avatar linchen2chris avatar luisrudge avatar mthahzan avatar pcurc avatar poovamraj avatar rnevius avatar sarachicad avatar sdacunha avatar sebirdman avatar snyk-bot avatar stevehobbsdev avatar stigi avatar travisobregon avatar trondwh avatar tyfrth avatar widcket avatar zchryst 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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

react-native-auth0's Issues

Missing Auth0 Domain

We got the following error:

2017-06-15 at 7 54 pm

It appears the API changed just before v1.0.0 was released. There wasn't an obvious way that this was communicated and I didn't see any reference to this error elsewhere. If anyone else runs into it this will hopefully point them in the correct direction.

Instantiating Auth0 used to take a string which was the Auth0 domain and now requires an object containing the domain and clientId.

MFA support

Is there going to be MFA support for this SDK? Or is it only available through the Lock SDK?

Update from beta to 1.0.2, can't login anymore

Hi, I just updated from the beta version to 1.0.2 and the login doesn't work anymore I think mostly because I don't understand what's related to the realm

My previous code that was working:

auth0
      .authentication(CLIENT_ID)
      .login(username, password, 'Username-Password-Authentication', {
        device: 'phone',
        scope: 'openid offline_access',
      })

New code

const auth0 = new Auth0({ domain: AUTH0_URL, clientId: CLIENT_ID });
// ...
auth0
      .auth
      .passwordRealm({
        email: username,
        username,
        password,
        realm: 'Username-Password-Authentication',
        scope: 'openid offline_access',
      })

I've also tried with realm: 'database' but it doesn't work.

I always get Error: Unauthorized

😒

Authentication API userInfo causes Unexpected token

React Native v0.27

Error message:

Unexpected token U in JSON at position 0
SyntaxError: Unexpected token U in JSON at position 0

Replicate by doing:

      lock
              .authenticationAPI()
              .userInfo(token.idToken)
              .then(response => console.log(response))
              .catch((err) => console.log(err))

response is not defined

I'm getting this error(1st image below), but when it returns, shows a message saying that response is not defined(2nd image below)

image

image

Could not invoke A0Auth.showUrl

I followed the quick start for react-native.
Now I'm trying to show the login page with
auth0.webAuth .authorize({ scope: 'openid email', audience: 'https://ramtin.auth0.com/userinfo' }) .then(credentials => console.log(credentials)) .catch(error => console.log(error));

But I'm getting "Could not invoke A0Auth.showUrl" error

"react-native": "0.44.0",
"react-native-auth0": "^1.0.3",

Inconsistent error from `createUser` promise

When running from iOS Simulator, I get one of the following errors in error.name:

  • user_exists = email already in use
  • username_exists = username already in use
  • invalid_password = it includes a detailed explanation in error.message.verified and error.message.rules

However, when running on the device, I always get the same error:

TypeError: Error.captureStackTrace is not a function (In 'Error.captureStackTrace(_this,_this.constructor)', 'Error.captureStackTrace' is undefined)

image uploaded from ios

oauthParameters of undefined

When I do this on Android (haven't tested it on ios yet:

auth0
    .webAuth
    .authorize({scope: 'openid email'})
    .then(credentials => console.log(credentials))
    .catch(error => console.log(error))

It throws this error:

TypeError: Cannot read property 'oauthParameters' of undefined
    at agent.js:27
    at tryCallTwo (core.js:45)
    at doResolve (core.js:200)
    at new Promise (core.js:66)
    at Agent.newTransaction (agent.js:26)
    at WebAuth.authorize (index.js:50)

I am using React Native Navigation (Wix).
React Native v0.46.

Manifest is this:

<activity
        android:name=".MainActivity"
        android:label="@string/app_name"
        android:launchMode="singleTask"
        android:configChanges="keyboard|keyboardHidden|orientation|screenSize"
        android:windowSoftInputMode="adjustResize">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
        <intent-filter>
            <action android:name="android.intent.action.VIEW" />
            <category android:name="android.intent.category.DEFAULT" />
            <category android:name="android.intent.category.BROWSABLE" />
            <data
                android:host="woodyshousing.eu.auth0.com"
                android:pathPrefix="/android/${applicationId}/callback"
                android:scheme="${applicationId}" />
        </intent-filter>
      </activity>

Is this library maintained or should we explore other options?

@hzalaz Is this library being maintained and will pull requests be accepted in appropriate timeframes? Looking for a auth0 solution for react-native and trying to decide if we should create our own internal framework or contribute to this.

Things that are missing that we would add:

  • Social
  • Forgot Password

Additionally we would like add more features as they become available in our app.

auth0.auth.passwordRealm always return 401 access_denied (missing client secret)

I spent two days trying to make the passwordRealm() function to work without any success.

I configured my client to have the correct grant type password with realm support by patching my client as explained in https://auth0.com/docs/api-auth/tutorials/password-grant#realm-support

And when sniffing the api calls, the Auth0 module produce this HTTP request that always return 401 access_denied:

POST /oauth/token HTTP/1.1
Host: MY_TENANT.eu.auth0.com
Content-Type: application/json
Connection: keep-alive
Accept: application/json
auth0-client: XXXX=
Accept-Language: en-us
Content-Length: 209
Accept-Encoding: gzip, deflate
User-Agent: Test/1 CFNetwork/811.4.18 Darwin/16.6.0

{
	"username": "[email protected]",
	"password": "mypassword",
	"realm": "Username-Password-Authentication",
	"client_id": "XXXXXXX",
	"grant_type": "http://auth0.com/oauth/grant-type/password-realm"
}

And after looking closely to the above link, I found that the client_secret was missing from the request. So I tried hacking a little bit the current module with this code:

function password(parameters = {}) {
    const payload = apply({
        parameters: {
            username: { required: true },
            password: { required: true },
            audience: { required: false },
            scope: { required: false }
        }
    }, parameters);
    return this.client
        .post('/oauth/token', {
            ...payload,
            client_id: this.clientId,
            grant_type: 'http://auth0.com/oauth/grant-type/password-realm',
            realm: 'Username-Password-Authentication',
            client_secret: 'XXXXX'    //<-----  ADD THE CLIENT SECRET HERE !!!
        })
}

const auth0 = new Auth0({
    domain: 'MY_DOMAIN',
    clientId: 'MY_CLIENT_ID',
})

const authWithPassword = password.bind(auth0.auth)

authWithPassword({ username: '[email protected]', password: 'XXXX', scope: 'openid' }).then(json => {
    console.log({
        success: true,
        json
    })
}).catch(error => {
    console.log({
        errorMsg: 'error',
        error
    })
})

And I finally managed to have my token back.

Unfortunately, it seems that there is no way to setup the client secret in the current API interface. Would it be possible to add it to the Auth0 constructor options ??

Thanks in advance!

No callback issue

Sorry for opening many issues, but since you closed the previous one, I had to open it again :D

I had to add quick workaround to receive back the callback. I added setTimeout.

Maybe there is a better solution ?

https://github.com/auth0/react-native-auth0/blob/master/networking/index.js

    return fetch(url, options)
      .then((response) => {
        const payload = { status: response.status, ok: response.ok, headers: response.headers };
        setTimeout(() => null, 0); <!--- quick fix which solves the promise issue ---->
        return response.json()
          .then((json) => {
            return { ...payload, json };
          })
          .catch(() => {
            return response.text()
              .then((text) => {
                return { ...payload, text };
              })
              .catch(() => {
                return { ...payload, text: response.statusText };
              });
          });
      });

Firebase auth (via custom token) not working

I can authenticate to Auth0 ok. This example is via uid/pwd.

Note:
In Auth0 web console, FIREBASE has been enabled and I have pasted in the Private Key Id, Private Key and Client Email values (that FIREBASE gives me via the Service Accounts tab in their web console) into Auth0 Firebase API Add On "Settings" view. Simple copy/paste. When I save it, Auth0 says 'saved successfully'. This is for an IOS project in Auth0.

Note 2:
We were advised by Auth0 support to add a Rule. Here it is:

function (user, context, callback) {
  var isFirebase = context.isDelegation && context.request.body.api_type === "firebase";
 
  if (isFirebase) {
    var identity = user.identities[0];
    user.firebase_data = {
      uid: identity.provider + ":" + identity.user_id,
      email: user.email,
      test: user.user_metadata
    };
    console.log(user);
  }
  return callback(null, user, context);
}

Now, back to the auth flow :

When the uid/pwd login completes to AUTH0 , I then receive a return payload from Auth0 that includes an "id_token" and an "access_token"

ok great. at this point, because i have enabled Firebase in Auth0 (via "Addon" connections as explained above) for this iOS app - I must assume that the id_token I am getting back from Auth0 has magically been made ready - to be then passed along to the Firebase login call.

So, I then pass the "id_token" INTO the Firebase authentication call.

The response is an ERROR!!:
The custom token format is incorrect. Please check the documentation.

Here is the code block:

auth0
   .authentication('yyyyyxxxxxxxxxxxxxCjxJjbIis')
   .login("[email protected]", "password", "myconnection")
   .then(credentials => {

      //now need to call delegation endpoint
      auth0
      .authentication('xxxxxxxx')
      .delegation(credentials.id_token, 'id_token', 'firebase', {scope : 'openid name email displayName'})
      .then( response => {

          //look out Firebase here goes......!
          firebase.auth().signInWithCustomToken(response.id_token).catch(function(error) {
             // Handle Errors here.
             var errorCode = error.code;
             var errorMessage = error.message;
             console.log(errorCode);
             console.log(errorMessage);
             // ...
          });

      })
      .catch(error => console.log(error));

   })
   .catch(error => console.log(error));

For reference the DECODED id_token (using https://jwt.io/#debugger):

HEADER:ALGORITHM & TOKEN TYPE
{
"typ": "JWT",
"alg": "RS256",
"kid": "3a9c98xxxxxx86ec694ad"
}

PAYLOAD:DATA
{
"uid": "auxxxxxxxxxxxxx7190",
"claims": {
"uid": "autxxxxxxxxxxxx7190",
"email": "[email protected]"
},
"iat": 14xx90,
"exp": 1480xxxxx0,
"aud": "https://identitytoolkit.googleapis.com/google.identity.identitytoolkit.v1.IdentityToolkit",
"iss": "[email protected]",
"sub": "[email protected]"
}

Lastly, we went to the REST API tests page here: https://auth0.com/docs/api/authentication#!#post--delegation

same/similar error with this response:

{
  "error": "invalid_token",
  "error_description": "invalid aud: https://identitytoolkit.googleapis.com/google.identity.identitytoolkit.v1.IdentityToolkit",
  "statusCode": 401
}

We are going rapidly insane trying to get this authentication via Auth0 -> Firebase to work. Perhaps just the documentation is lacking. Either way can someone please look at this and help to resolve. We'd be happy to update your docs on Github for the React Native api once this thing starts working.

Catch the whole returned object

I'm want to output an error message when the user tries to login with wrong credentials. I'm using this code to login the user:

auth0
    .auth
    .passwordRealm({username: "[email protected]", password: "password", realm: "myconnection"})
    .then(console.log)
    .catch(console.error);

When I try this with wrong credentials I never end up in then and what I receive in the catch function is just a message, but not the returned object from the server?

How can I inspect the returned error object?I want to display my custom error in the app? Just showing the error message that comes from auth0 is not enough.

Logout?

Is there a logout function corresponding to webAuth.authorize? There is an logout function for the webAuth library in auth0.js for web based clients. How does a react-native user logout with react-native-auth0?

Currently, even though I can logout the user out of the app by destroying local state, the user remain logged in at the social provider and so is not prompted for credentials when they try to log in again.

Version 1

It seems that it's been a few months since any work was done here.
Could we consider the beta final then and do a proper release ? :D:D

Not able to login with linkedin

I am new to auth0.

I am trying to understand the wrapper.
It did work with authlock .But I cannot make it work with this auth0.

const auth0 = new Auth0('saddsafas.auth0.com')
                                .authentication('213jjk1j3k12j3k123j')
                                .login('[email protected]', 'password', "LinkedIn")
                               .then(credentials => alert(credentials))
                               .catch(error => alert(error));

Am I doing something wrong?

screen shot 2017-06-14 at 23 11 21

Android "User Cancelled Auth" Error

screen shot 2017-07-11 at 12 02 19 pm

This is my onLogin command and what it does is it calls checkLogin which simply checks credentials and then navigates to new page if successful. This piece of code works perfectly on IOS and it navigates to the new page upon verifying the accessToken after pressing login and entering correct login info.

However, on Android the same code catches an error at line 54 after pressing login and entering correct login info.

screen shot 2017-07-11 at 12 03 17 pm

My callbacks are configured correctly and all.

logging out completely

I'm using facebook login with Auth0... logging out works fine, except it's not a true log out... it's a partial log out where only the local session is removed from AsyncStorage, however, facebook continues to remember the user, which makes it impossible for a different facebook user to login on the same device, unless you ask your user to delete the app and re-install, which is not an acceptable thing to ask users to do, especially at scale. Is there a way to make the app not remember/store any facebook info, so that new users can login?

oauth/token endpoint incomplete

We recently created a new auth0 account that no longer supports /oauth/ro. The alternative is to use oauth/token, but that endpoint is incomplete here. It doesn't allow one to set the username, password, grant_type. And it should not require a verifier, redirect_uri, or code

Updating app_metadata

From what I've seen, there's no way to update app_metadata, as .patch only allows for user_metadata updating.

Any plans to allow for app_metadata support?

Not compatible with react-native 0.35.0

Hi, i'm currently haveing this configuration :
{
"name": "testAuth3",
"version": "0.0.1",
"private": true,
"scripts": {
"start": "node node_modules/react-native/local-cli/cli.js start"
},
"dependencies": {
"react": "15.3.2",
"react-native": "0.35.0",
"react-native-auth0": "^1.0.3"
}
}

and i'm using your example : https://auth0.com/docs/quickstart/native/react-native
which states, that is React Native 0.26.0 compatible.
I didn't managed to get it working : the problem in XCode is :
"AppDelegate.m:14:9: 'React/RCTLinkingManager.h' file not found"

I would like to use your solution, as a API, I've already spent several days, but no success.
Using the latest version of React-Native is OK.
But i can't migrate my application right now, because of time question.
If anyone has a solution, i'm very interested.

Thanks in advanced,

Delegation and refreshToken usage

I'm using 0.0.1 and seems like 1.0.0 has changed delegation method.
Could you provide those usages?

About refreshToken()
I haven't test it yet but i had look in the code, in line 139, it hard-coded third argument to 'app'.
I'm using firebase, should it be an options there?

How do I get user's last_login as seen in patch, without patch?

I was trying out the api and tried "Get user information" and "Patch user with user_metadata". I noticed during the patch that the response contained information that I would like such as last_login, however I don't see that when I just "Get user information". Right now I am merging the user_metadata with itself just to get that information, which seems like a bad idea...

Social login?

Does this library support social login?

When I try this:
.login("<EMAIL>", "<PASSWORD>", "facebook")

I get this error:
Error: specified strategy does not support requested operation (facebook)

I need to use Auth0 for social login with a custom login UI.

webAuth redirect_uri doesn't work with app scheme (expects http:// or https:// )

Hi,
I'm having trouble getting the webAuth method to work.

webAuth sets the redirect URI with the bundle identifier as the scheme
${bundleIdentifier.toLowerCase()}://${domain}/${Platform.OS}/${bundleIdentifier}/callback

I get sent to the /authorize url in the chrome custom tab, but that has an 'oops, something went wrong' error.

this is my auth0 log result:

The redirect_uri parameter is not valid: "com.my_app://my_domain.auth0.com/android/com.my_app/callback" If url looks fine, check that you are not including non printable chars

If I add https:// to the beginning of the redirect uri, it works and renders the login page (although that redirect uri doesn't exist).

Is there some part of setup within auth0 I need to do to allow this to work?

my client type is set to native and I have added the redirect_uri to the allowed callback urls.

Thanks!

Customizing Lock Screen not woking

Hello,

i tried to customize the lock screen. I like to change the language and logo. Unfortunately the config options are not taken in to account.

Best regards,
Manuel


lock.show({
      closable: true,
      theme: {
        logo: 'https://avatars3.githubusercontent.com/u/5859486?v=3&s=466',
         primaryColor: 'green'
      },
      languageDictionary: {
          emailInputPlaceholder: "[email protected]",
          title: "Log me in"
      }
    }, (err, profile, token) => {
      if (err) {
        console.log(err);
        return;
      }
      this.props.navigator.push({
        name: 'Profile',
        passProps: {
          profile: profile,
          token: token,
        }
      });
    });

No callback after webauth authentification.

const auth0 = new Auth0('alexandr.auth0.com')
.webAuth('asdasdfssafasf')
.authorize({connection: 'linkedin'})
.then(credentials => console.log('credentials', credentials))
    .catch(error => console.log('ERROR', error));

I successfully sign in with webauth using my linkedin account, but I dont recieve any callback or tokens back.

Middleware to re-issue tokens on failed http call

Based on this post I'm trying to implement the sliding session. Is there some middleware that exists in RN-auth0 so that it can detect a failed call (expired access token) and do a reissue of tokens (using locally stored refresh token) automatically? Seems like a good feature to have if I'm understanding this properly.

Error: Activity class ... does not exist

Is this a bug report?

Yes

Have you read the Bugs section of the Contributing to React Native Guide?

Yes

Environment

  1. react-native -v: 0.45 & 0.46.1
  2. node -v: v6.9.1
  3. npm -v: 3.10.8
  4. yarn --version (if you use Yarn): 0.17.6

Then, specify:

  1. Target Platform (e.g. iOS, Android): Android
  2. Development Operating System (e.g. macOS Sierra, Windows 10): macOS Sierra

Steps to Reproduce

  • Create a new react-native project using react-native init ExampleProject
  • Add auth0 with yarn add react-native-auth0 and link it react-native link react-native-auth0
  • And configure the Android project: https://github.com/auth0/react-native-auth0#configuration
  • Add Redux, React Navigation and a few other JS libraries.

Expected Behavior

App should run without any kind of errors.

Actual Behavior

When I want to run the app with react-native run-android after writing some code and adding logic without touching the native Java code and with a successful build, I get this error:

BUILD SUCCESSFUL

Total time: 10.072 secs
Running adb -s 0259749fb8c21037 reverse tcp:8081 tcp:8081
Starting the app on 0259749fb8c21037 (adb -s 0259749fb8c21037 shell am start -n com.woodyapplication/com.woodyapplication.MainActivity)...
Starting: Intent { cmp=com.woodyapplication/.MainActivity }
Error type 3
Error: Activity class {com.woodyapplication/com.woodyapplication.MainActivity} does not exist.

I managed to fix this with the following hacks:

  • creating a new project and copy the JS code over (which is not a solution)
  • replace the package name com.woodyapplication with com.woody.application (or something else). This fixes it for a few runs but then the error message appears again.

I've tested this with RN 0.45 and RN 0.46.1 the bug appears on both versions
Could `android:launchMode="singleTask" be the cause of this bug?

Failed Exchange - type: 'feacft'

Im trying to login with an Authorized google account, but i get "Unauthorized" in the app, and this is what i see in the logs:

fail

It returns a success and a second later it returns two Failed Exchange errors.

Here's my code:

auth0.webAuth
      .authorize({ scope: 'openid email', connection: 'google-oauth2' })
      .then(credentials => console.log(credentials))
      .catch(error => console.log(error));

and here is the Failed Exchange raw:

{
  "date": "2017-07-13T14:41:50.767Z",
  "type": "feacft",
  "description": "Unauthorized",
  "connection_id": "",
  "client_id": "xxxx",
  "client_name": null,
  "ip": "xxxx",
  "user_agent": "com.<appname>.<appname>/8 CFNetwork/808.2.16 Darwin/16.0.0",
  "user_id": "",
  "user_name": "",
  "auth0_client": {
    "name": "react-native-auth0",
    "version": "1.0.3"
  },
  "log_id": "xxxx"
}

The same account works fine when i use react-native-lock to login.

Additional info

  • react-native: 0.45.0
  • react-native-auth0: 1.0.3
  • Platform: Android and iOS

Nonce is no longer accepted?

I submitted a patch (#3) to address this awhile back but it looks like it is missing. Is this an intentional omission or would it be welcomed for me to re-add it?

Thanks!

A0Auth0 object undefined

I installed react-native and this library but when I tried running I got:

[TypeError: undefined is not an object (evaluating 'A0Auth0.oauthParameters')]

I tried looking into this and it seems that in webauth/index.js on line 11 the react-native object NativeModules does not contain A0Auth0. I looked into the react-native repo code and found no mention of A0Auth0 so maybe this repo isn't compatible with the latest version of react-native?

What's the fix for this?

Failed Exchange

Baby steps...

I have the following code:

	  auth0
		  .auth
		  .passwordRealm({username: "xxxx@yxxx", password: "123456ab", realm: "Username-Password-Authentication"})
		  .then((res) => console.log(res))
		  .catch(err => console.error(err));

and I get an "internal server error occurred". I had a look at my logs and I see this:

{
  "date": "2017-06-28T08:38:54.359Z",
  "type": "feccft",
  "description": "Unauthorized",
  "connection_id": "",
  "client_id": "xxxx",
  "client_name": null,
  "ip": "52.28.56.226",
  "user_agent": "node-superagent/2.3.0",
  "user_id": "",
  "user_name": "",
  "audience": "https://xxxx/api/v2/",
  "scope": null,
  "log_id": "xxxx"
}

What am I doing wrong here? I actually created the user with the library.

auth0
   	  .auth
   	  .createUser({email: 'xxx@xxx', username: 'xxx@xxx', password: '123456ab',
             connection: 'Username-Password-Authentication'})
   	  .then(console.log)
   	  .catch(console.error);

So I'm not sure what the issue with the login might be?

[Auth0 API] [email protected] not compatible Auth0 API

I try to use the Auth0 API, instead of the Lock (because of issues concerning the grant authorization), but it seems it’s not compatible with [email protected] (my case).

I would like to know, if in my configuration it is possible to use Auth0 API or not.
Upgrading react-native version, it is not a possibility right now.

Thank you in advance
Gilles

error: auth0.authenticationAPI is not a function

Hi, I appear to get this error message in RN when trying to use the authenticationAPI: 'auth0.authenticationAPI is not a function'

I've installed via npm correctly and my code is below. Do you know of any reason why this might give me an error? Many thanks

const Auth0 = require('react-native-auth0')
const auth0 = new Auth0('MYACCOUNT.auth0.com')
...
auth0
            .authenticationAPI()
            .delegation({
                "id_token": "user token"
                // Other Delegation parameters
            })

ADFS on IOS is not working.

I'm not sure if I should ask here, so if I'm wrong or I didn't follow the rules, please accept my apologize.
I will move my question to other place.
I run the auth0-react-native-sample base on the react-native-auth0.
https://github.com/auth0-samples/auth0-react-native-sample

Everything works fine on android, however, the adfs single sign on is not working with IOS.
In IOS, after I entered the account and pressed the login button. It only shows me a loading image.
But, there will be a box popped out for me to enter the adfs account and password in android.

So, I would like to ask what can I do to solve this problem? Or any suggestions for me?
Thank You!

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.