Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

I am not able to get the url and return to my app #442

Open
eliasg52 opened this issue Nov 30, 2023 · 13 comments
Open

I am not able to get the url and return to my app #442

eliasg52 opened this issue Nov 30, 2023 · 13 comments

Comments

@eliasg52
Copy link

Which platform(s) does your issue occur on?

  • Android

Please, provide the following version numbers that your issue occurs with:

  • CLI:
    react-native-cli: 2.0.1
    react-native: 0.71.2

  • Plugin(s):
    "react-native-inappbrowser-reborn": "^3.7.0",

Please, tell us how to recreate the issue in as much detail as possible.

Hello how are you? Could someone give me a hand please I have read all the issues and examples but I can't get it to work with all the forms I tried from this repo. I am trying to log in with Twitch and then return to my app and be able to take the value of the accesstoken from the url, I can open the page corresponding to it and press the authorize button, then the app stays at the url of the type : http://localhost:4200/twitch/callback#access_token=uvhi6536vgf9farse6y2kbf6k8i1il&scope=openid+user%3Aread%3Aemail+channel%3Amanage%3Abroadcast+channel%3Aread%3Astream_key&token_type=bearer. But to return to my app I have to press the x button otherwise it does not return, and I also have no way of taking the access token from the url because when I return to my app the result is like: {"message": "chrome tabs activity closed", "type": "cancel"}. In addition to the code, I attached a video with the behavior I am having. Thanks!

Is there any code involved?

FUNCTION TO OPEN THE WEBVIEW

` const openLink = async () => {
const url =
'https://id.twitch.tv/oauth2/authorize?&response_type=token' +
'&client_id=' +
process.env.CLIENT_ID_TWITCH +
'&redirect_uri=' +
process.env.REDIRECT_URI_TWITCH + //process.env.REDIRECT_URI_TWITCH is: http://localhost:4200/twitch/callback
'&scope=' +
process.env.SCOPE_TWITCH +
'&force_verify=true';

console.log(url);

const isAvailable = await InAppBrowser.isAvailable();

if (isAvailable) {
  InAppBrowser.openAuth(url, process.env.REDIRECT_URI_TWITCH, {
    showTitle: true,
    toolbarColor: '#6200EE',
    secondaryToolbarColor: 'black',
    navigationBarColor: 'black',
    navigationBarDividerColor: 'white',
    enableUrlBarHiding: true,
    enableDefaultShare: true,
    forceCloseOnRedirection: false,
    showInRecents: true,
    // Specify full animation resource identifier(package:anim/name)
    // or only resource name(in case of animation bundled with app).
    animations: {
      startEnter: 'slide_in_right',
      startExit: 'slide_out_left',
      endEnter: 'slide_in_left',
      endExit: 'slide_out_right',
    },
    headers: {
      'my-custom-header': 'my custom header value',
    },
  }).then(response => {
    console.log(response);
    /*   console.log(response.url); */
  });
} else Linking.openURL(url);

};
`

ANDROID MANIFEST

I tried putting many values ​​as host but I don't know which one to put exactly.

`

<uses-permission android:name="android.permission.INTERNET" />

<application
  android:name=".MainApplication"
  android:label="@string/app_name"
  android:icon="@mipmap/ic_launcher"
  android:roundIcon="@mipmap/ic_launcher_round"
  android:allowBackup="false"
  android:theme="@style/AppTheme">
  <activity
    android:name=".MainActivity"
    android:label="@string/app_name"
    android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|screenSize|smallestScreenSize|uiMode"
    android:launchMode="singleTask"
    android:windowSoftInputMode="adjustResize"
    android:exported="true">
    <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:scheme="app_name" host="http://localhost:4200/" pathPrefix=""/>
    </intent-filter>
  </activity>
</application>
`
WhatsApp.Video.2023-11-30.at.13.28.28.mp4
@jdnichollsc
Copy link
Member

@eliasg52 hello mate, you can't redirect using localhost... the redirection only works using the right host depending on the platform, check more examples here: https://reactnavigation.org/docs/deep-linking/#setup-on-android

@jdnichollsc
Copy link
Member

BTW, I have an example here: https://github.com/proyecto26/react-native-inappbrowser/blob/develop/example/src/utils.ts#L90

As you can see I have a different url for each platform, so you can use something like that to pass the right redirect url and be able to redirect your users to the app again 👍

@eliasg52
Copy link
Author

@jdnichollsc thanks for your response, i change my code but i have the same behavior, I don't know why a sign keeps appearing indicating that it will be redirected to localhost:4200 if I am no longer using that environment variable in my redirect.

My code now:

const getDeepLink = (path = '') => { const scheme = 'my-demo'; const prefix = Platform.OS === 'android' ? ${scheme}://demo/:${scheme}://`;
return prefix + path;
};

const openLink = async () => {
const redirectUrl = getDeepLink();

const appUrl =
  'https://id.twitch.tv/oauth2/authorize?&response_type=token' +
  '&client_id=' +
  process.env.CLIENT_ID_TWITCH +
  '&redirect_uri=' +
  encodeURIComponent(redirectUrl) +
  '&scope=' +
  process.env.SCOPE_TWITCH +
  '&force_verify=true';

console.log('APPURL:', appUrl);
console.log('REDIRECT URL:', redirectUrl)

const isAvailable = await InAppBrowser.isAvailable();

if (isAvailable) {
  InAppBrowser.openAuth(appUrl, redirectUrl, {
    showTitle: false,
    enableUrlBarHiding: true,
    enableDefaultShare: false,
  }).then(response => {
    console.log(response);
    /*   console.log(response.url); */
  });
} else console.log('ERROR WEBVIEW');

};
`

ANDROID MANIFEST

`

<uses-permission android:name="android.permission.INTERNET" />

<application
  android:name=".MainApplication"
  android:label="@string/app_name"
  android:icon="@mipmap/ic_launcher"
  android:roundIcon="@mipmap/ic_launcher_round"
  android:allowBackup="false"
  android:theme="@style/AppTheme">
  <activity
    android:name=".MainActivity"
    android:label="@string/app_name"
    android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|screenSize|smallestScreenSize|uiMode"
    android:launchMode="singleTask"
    android:windowSoftInputMode="adjustResize"
    android:exported="true">
    <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:scheme="my-demo" android:host="demo" />
    </intent-filter>
  </activity>
</application>
`

Console.log

image

Video attached:

WhatsApp.Video.2023-11-30.at.17.42.32.mp4

@AndrewNes
Copy link

@jdnichollsc thanks for your response, i change my code but i have the same behavior, I don't know why a sign keeps appearing indicating that it will be redirected to localhost:4200 if I am no longer using that environment variable in my redirect.

My code now:

const getDeepLink = (path = '') => { const scheme = 'my-demo'; const prefix = Platform.OS === 'android' ? ${scheme}://demo/:${scheme}://`; return prefix + path; };

const openLink = async () => { const redirectUrl = getDeepLink();

const appUrl =
  'https://id.twitch.tv/oauth2/authorize?&response_type=token' +
  '&client_id=' +
  process.env.CLIENT_ID_TWITCH +
  '&redirect_uri=' +
  encodeURIComponent(redirectUrl) +
  '&scope=' +
  process.env.SCOPE_TWITCH +
  '&force_verify=true';

console.log('APPURL:', appUrl);
console.log('REDIRECT URL:', redirectUrl)

const isAvailable = await InAppBrowser.isAvailable();

if (isAvailable) {
  InAppBrowser.openAuth(appUrl, redirectUrl, {
    showTitle: false,
    enableUrlBarHiding: true,
    enableDefaultShare: false,
  }).then(response => {
    console.log(response);
    /*   console.log(response.url); */
  });
} else console.log('ERROR WEBVIEW');

}; `

ANDROID MANIFEST

`

<uses-permission android:name="android.permission.INTERNET" />

<application
  android:name=".MainApplication"
  android:label="@string/app_name"
  android:icon="@mipmap/ic_launcher"
  android:roundIcon="@mipmap/ic_launcher_round"
  android:allowBackup="false"
  android:theme="@style/AppTheme">
  <activity
    android:name=".MainActivity"
    android:label="@string/app_name"
    android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|screenSize|smallestScreenSize|uiMode"
    android:launchMode="singleTask"
    android:windowSoftInputMode="adjustResize"
    android:exported="true">
    <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:scheme="my-demo" android:host="demo" />
    </intent-filter>
  </activity>
</application>

`

Console.log

image

Video attached:

WhatsApp.Video.2023-11-30.at.17.42.32.mp4

I have a similar problem on Android

@krini
Copy link

krini commented Mar 1, 2024

Did you solve this? What was your fix?

@AndrewNes
Copy link

Did you solve this? What was your fix?

I found this error when I was making a shared authorization library for a group of my applications and this problem was found in the example of this library. The strange thing is that when I connected this library to the main project, everything worked. To be honest, I could not figure out exactly what the problem was in this example (As a result, the same code works in the main project and does not work in the example library, which remains a mystery to me, especially considering the fact that the dependencies are exactly the same).

@AndrewNes
Copy link

Did you solve this? What was your fix?

And I also realized that this problem does not depend on the "react-native-inappbrowser" library at all. The problem is with react-native deep links.

@AndrewNes
Copy link

Did you solve this? What was your fix?

After digging into discussions of similar problems in the react-native repository (or rather, going through all the discussions on this topic), I found nothing better than redefining Intent in MainActivity. But this did not solve my problem in the example of my library.
I'll duplicate the code from that answer for you (facebook/react-native#24624).

  @Override
    public void onNewIntent(Intent intent) {
        if (intent.getData() != null) {
          Uri deepLinkURL = intent.getData();
          // note deeplink_identifier means the identity that you register in the manifest.
          if (deepLinkURL.toString().contains("deeplink_identifier")) {
              // Create map for params
              WritableMap event = Arguments.createMap();
              // Put data to map
              event.putString("url", deepLinkURL.toString());
              // Get EventEmitter from context and send event thanks to it
              getReactInstanceManager().getCurrentReactContext()
                      .getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
                      .emit("url", event);
          } else {
             // to handle other deeplink that not related to the defined deeplink identifier such as notification
             setIntent(intent);
          }
        }
    }

@AndrewNes
Copy link

If you are lucky enough to find out the solution to this problem, I will be grateful if you tell me what the solution was ;)

@krini
Copy link

krini commented Mar 8, 2024

If you are lucky enough to find out the solution to this problem, I will be grateful if you tell me what the solution was ;)

It looks like our issue is not in react-native-inappbrowser, but at the login provider. Right now we solve it by showing a button to the user that triggers the redirect.

@vaishnavme
Copy link

Similar issue. I'm not sure what's wrong.

I have Product Hunt oAuth on the website and need it for the mobile app.

REDIRECT_URI = https://my-site/profile/authCallback

authURL = https://api.producthunt.com/v2/oauth/authorize?client_id=${PRODUCT_HUNT_CLIENT_ID}&redirect_uri=${REDIRECT_URI}&response_type=code&scope=public+private

mobileSchema = myapp://profile/authCallback;

Code:

 const response = await InAppBrowser.openAuth(authURL, mobileSchema, {
        ephemeralWebSession: false,
        showTitle: false,
        enableUrlBarHiding: true,
        enableDefaultShare: false,
      });

After authentication, it should open myapp://profile/authCallbackon mobile, Right now InAppBrowser opens REDIRECT_URI after authentication. also response only logs when I click on cancel.

Constraints

  • Cannot replace REDIRECT_URI with mobileSchema on the OAuth provider because it will fail OAuth on the website.
  • Cannot create two separate applications on OAuth provider with different callback URLs (one for web and another for mobile)

Just so you know, I'm NOT using the localhost URL while working on the flow.
npx uri-scheme open "myapp://profile/authCallback" --ios command open the required screen.

Question:

  • Do we need mobileSchema and REDIRECT_URI same to make it work?
  • Is there a way to know URL changes in InAppBrowser?

@krini
Copy link

krini commented Jun 4, 2024

No, you cannot see the url

Question:

  • Is there a way to know URL changes in InAppBrowser?

@vaishnavme
Copy link

Similar issue. I'm not sure what's wrong.

I have Product Hunt oAuth on the website and need it for the mobile app.

REDIRECT_URI = https://my-site/profile/authCallback

authURL = https://api.producthunt.com/v2/oauth/authorize?client_id=${PRODUCT_HUNT_CLIENT_ID}&redirect_uri=${REDIRECT_URI}&response_type=code&scope=public+private

mobileSchema = myapp://profile/authCallback;

Code:

 const response = await InAppBrowser.openAuth(authURL, mobileSchema, {
        ephemeralWebSession: false,
        showTitle: false,
        enableUrlBarHiding: true,
        enableDefaultShare: false,
      });

After authentication, it should open myapp://profile/authCallbackon mobile, Right now InAppBrowser opens REDIRECT_URI after authentication. also response only logs when I click on cancel.

Constraints

  • Cannot replace REDIRECT_URI with mobileSchema on the OAuth provider because it will fail OAuth on the website.
  • Cannot create two separate applications on OAuth provider with different callback URLs (one for web and another for mobile)

Just so you know, I'm NOT using the localhost URL while working on the flow. npx uri-scheme open "myapp://profile/authCallback" --ios command open the required screen.

Question:

  • Do we need mobileSchema and REDIRECT_URI same to make it work?
  • Is there a way to know URL changes in InAppBrowser?

Got it working

Only 2 changes I did

  1. Auth URL change
    const authURL = `https://api.producthunt.com/v2/oauth/authorize?client_id=${PRODUCT_HUNT_CLIENT_ID}&redirect_uri=${REDIRECT_URI}&response_type=code&scope=public+private&state=mobile"

In authURL, I'm adding state=mobile. It's important to use state query. any other custom query will get removed on redirect

  1. On website
    After the auth, the user gets redirected to https://my-site/profile/authCallback this path. I have added one check ion this page
useEffect(() => {
  if(router.query.state === 'mobile') {
   window.location.href = "myapp://profile/authCallback";
 }
},[])

with this users get redirected to mobile schema & handled by deep link.

 const result = await InAppBrowser.openAuth(authURL, redirectURL, {
        dismissButtonStyle: 'cancel',
        showTitle: false,
        enableUrlBarHiding: true,
        enableDefaultShare: true,
      });

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

5 participants