B4A Class [class][B4X] Microsoft OAuth2

Hi there:

I've adapted Erel's Google Oauth2 class to login with Microsoft, adapting the code from this post (thanks @stu14t)

For now, it's just working on B4A. Works in B4A and B4J, not tested in B4i. Probably with @Erel help it will work in other platforms

MicrosoftOAuth2 class takes care of several tasks:

1. Opening the browser and getting the authorization code.
2. Getting and saving the access token and refresh token from the authorization code.
3. Getting a new access token when it expires using the refresh token.

Setup

1. Go to https://entra.microsoft.com ->Aplication Developer->Register app. After registering your app, you will need your client_id and your tenant_id
2. Configure your “API permissions”. You will need, at least “User.Read” permissions, and you have to see the green check. (I can't test the sendMail because I got no permissions from my IT Manager. You need the Mail.Send permission)



B4A

3. Go to “Authentication” and “Add a platform”. Select “Android”. Set the package name (MUST be the Package Name set in the IDE (Ctrl-B))



IMPORTANT: Package name (Nombre del paquete in the next image) must be the same that in the IDE
"Sign HASH" (Hash the firma in the image) must be your Private key, in base64 format. In the example you will get your private key base64 hash in LOGS if you run the app. Copy it, and paste in the Microsoft page: (code from this post)

B4X:
Log("Use this sha1 base64 sign to register your app in ms: " & su.EncodeBase64(raw))
result:
Use this sha1 base64 sign to register your app in ms: 2pmj9i4rSx0yEb/viWBYkE/ZQrk= ‘FAKE




Using that code in the microsoft page you will get a “redirection URI” you must use it in order the browse redirects to your app



Add to your APP Manifest this code, in order the browser returns to your app after login
B4X:
AddActivityText(Main,
<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="msauth"
android:host="$PACKAGE$"
android:path="2pmj9i4rSx0yEb/viWBYkE/ZQrk=" ‘The same you get in your LOG app
/>
</intent-filter>

B4J

Go to “Authentication” and “Add a platform”. Select “Mobile and Desktop apps”. In redirection_uri add: http://127.0.0.1:51067



Set the client_id and tenant_id in B4XMain, and test!!

Any improvement is welcome!!




 

Attachments

  • 1731253058949.png
    67.1 KB · Views: 11
  • B4XMSLogin.zip
    24.5 KB · Views: 9
Last edited:
Cookies are required to use this site. You must accept them to continue using the site. Learn more…