Code Monkey home page Code Monkey logo

Comments (6)

moberwasserlechner avatar moberwasserlechner commented on August 10, 2024

Could you plz share your config as I dont know the provider (without any credentials ofcourse) but I need to see how you configured the plugin.

from generic-oauth2.

maggix avatar maggix commented on August 10, 2024

The information here come from a lot of documents/sample code/googling, but if there is a Microsoft reference, happy to read about it. Warning: Long post, but hopefully comprehensive.

The main ref for building the OAuth flow on Azure B2C is this page: /https://docs.microsoft.com/en-us/azure/active-directory-b2c/active-directory-b2c-reference-oauth-code
Azure B2C uses a "Policy" parameter specified for the app configuration page on Azure (in my case B2C_1_sign-up_sign-in ).
This is used as it is passed as the ?p=... parameter in the Microsoft documentation, since this plugin does not have a parameter for this config, I decided to include it in the URL as per this sample: https://github.com/Azure-Samples/active-directory-b2c-javascript-msal-singlepageapp

const authOptions = {
      appId: "<App ID from Azure B2C App Registration page>",
      authorizationBaseUrl:
        "https://testazureb2corganization.b2clogin.com/testazureb2corganization.onmicrosoft.com/B2C_1_sign-up_sign-in/oauth2/v2.0/authorize",
      accessTokenEndpoint:
        "https://testazureb2corganization.onmicrosoft.com/B2C_1_sign-up_sign-in/oauth2/v2.0/token",
      scope:
        "https://testazureb2corganization.onmicrosoft.com/api/user_impersonation",
      responseType: "token", 
      web: {
        redirectUrl: window.location.origin
      },
     android: {
        redirectUrl: "com.testapp.ionicreact://oauth",
        customScheme: "com.testapp.ionicreact://"
      },
      ios: {
        redirectUrl: "capacitor://localhost",
        customScheme: "capacitor://"
      }
    };

The iOS project is configured with this URL registered to the app:

<key>CFBundleURLTypes</key>
	<array>
		<dict>
			<key>CFBundleURLName</key>
			<string>com.getcapacitor.capacitor</string>
			<key>CFBundleURLSchemes</key>
			<array>
				<string>capacitor</string>
			</array>
		</dict>
	</array>

This is the login code:

const login = () => {
      console.log("About to login");
      OAuth2Client.authenticate(authOptions)
        .then(resourceUrlResponse => {
          let accessToken = resourceUrlResponse["access_token"];
          let oauthUserId = resourceUrlResponse["id"];
          let name = resourceUrlResponse["name"];
          // go to backend
          // history.push('/home');
          console.log("Token: " + accessToken);
        })
        .catch(reason => {
          console.error("OAuth rejected", reason);
        });
    };

Reference app configuration on Azure B2C:
Screenshot 2019-08-13 at 14 39 04

(Note that it's not possible to add a Redirect URI for native apps like scheme:// , it has to be in the format scheme://path )

The iOS project flow (working) is:

  • tap on a button "Authenticate"
  • a Safari window opens, with Azure B2C login page
  • I enter user+password and tap "Login"
  • the redirect uri kicks in and returns me to the app
  • I get the token using Capacitor's App plugin App.addListener('appUrlOpen', (data) => {...

The Android flow (not working) is:

  • tap on a button "Authenticate"
  • the Azure B2C login page opens in the app itself
  • I enter user+password and tap "Login"
  • I am prompted if I want to open the page in Chrome (expected behavior: this should not happen)
  • the browser page opens with "Bad request" error

Android project is configured correctly on the MainActivity, as explained before. Also, build.gradle contains:

android.defaultConfig.manifestPlaceholders = [
        'appAuthRedirectScheme': 'com.testapp.ionicreact'
]

Screenshots:

Screenshot 2019-08-13 at 14 41 59

Screenshot 2019-08-13 at 14 42 31

Screenshot 2019-08-13 at 14 42 43

As I mentioned before, I can't seem to reach breakpoints in the native Android code of the plugin (while I do reach breakpoints in MainActivity, for example), not sure if that's the expected behavior

from generic-oauth2.

maggix avatar maggix commented on August 10, 2024

Update: it seems like I had a problem on my end which resulted, as identified, in only the web code being called and not native code. Strangely enough the flow would not give error on iOS.
Will update the config above/share the working one after I manage to get to a successful flow-which is not yet the case.

Anyway, specific to this issue: this code opens the Web flow:

OAuth2Client.authenticate(authOptions)

For calling the plugin on Android, it needs to be (as per README):

Plugins.OAuth2Client.authenticate(authOptions)

More findings while going through this research:

  • the Android plugin code is overriding any additionalParameters with android parameters. I will submit a PR as this is giving problems with Azure AD B2C which requires a ?p= param added to the URL.
  • Setting the app's scheme in both build.gradle and in AndroidManifest.xml results in a "conflict" as described here: FormidableLabs/react-native-app-auth#130

So I am configuring build.gradle like this:

android.defaultConfig.manifestPlaceholders = [
        'appAuthRedirectScheme': 'com.testapp.ionicreact'
]

and the custom_url_scheme as:

    <string name="custom_url_scheme">com.testapp.ionicreact.intent</string>

(setting them the same results in the same app displayed twice as "Open with" after authentication)

Now I am facing an error of type: ERR_STATES_NOT_MATCH, with this line in the debug console:

W/AppAuth: State returned in authorization response (null) does not match state from request (WboWKqMvEbm9ueZnM0GF) - discarding response

Which is strange considering that the intent data (dataIntent) in the response received in handleOnActivityResult actually does contain the token in the uriString param of mData object:

com.testapp.ionicreact://oauth2/redirect#state=1Bh407zGCRCNMNFRNG7v&access_token=<the token>&token_type=Bearer&expires_in=3600

(Note: I had to use com.testapp.ionicreact://oauth2/redirect as Azure AD B2C does not allow using only the app scheme for redirect url com.testapp.ionicreact://)

from generic-oauth2.

maggix avatar maggix commented on August 10, 2024

Final update: Android and iOS both work, using this config:

const authOptions = {
     appId: "<the app id>",
      authorizationBaseUrl:
        "https://testazureb2corganization.b2clogin.com/testazureb2corganization.onmicrosoft.com/oauth2/v2.0/authorize",
      accessTokenEndpoint:
        "https://testazureb2corganization.onmicrosoft.com/oauth2/v2.0/token",
      scope:
        "https://testazureb2corganization.onmicrosoft.com/api/user_impersonation", //add offline_access openid
      //?p=B2C_1_sign-up_sign-in
      responseType: "token", //default = token, try with code"
      web: {
        redirectUrl: window.location.origin
      },
      android: {
        customScheme: "com.testapp.ionicreact://oauth",
      },
      ios: {
        customScheme: "com.testapp.ionicreact://oauth",
      },
      additionalParameters: {
        p: "B2C_1_sign-up_sign-in",
        response_mode: "query"
      }
    };

(note the response_mode as query so that parameters are passed after ? and not #, which causes the native libraries to fail parsing the response. )

However this required some code changes in the native iOS and Android code, to support the additional p parameter and the "token" flow (it seems the Android code is designed to support both "code" and "token", but only the "code" success is properly handled?).
Will submit a PR to discuss this. I am closing this issue

from generic-oauth2.

Sampath-Lokuge avatar Sampath-Lokuge commented on August 10, 2024

Hi @maggix

Can we have your PR for this issue? Thanks in advance.

from generic-oauth2.

Rajarml avatar Rajarml commented on August 10, 2024

Hi @maggix ,

I'm interested too by your modification as I'm trying to use this lib for MSAL Oauth2.

from generic-oauth2.

Related Issues (20)

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.