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

AADSTS650052: The app is trying to access a service 'serviceID'(Microsoft Mobile Application Management) that your organization lacks a service principal for. #239

Open
jayanth-quintet opened this issue Aug 10, 2024 · 16 comments
Assignees

Comments

@jayanth-quintet
Copy link

Intune Android App SDK Policy Enforcement Issue

Questions to Ask Before Submission

  1. Have you completed the exit criteria for each phase in the [Intune App SDK for Android Integration Guide]?

Yes

  1. Have you checked the [Microsoft Intune App SDK for Android] repository for similar issues?

Yes

  1. Are you using the latest version of the [SDK]?

MSAL SDK version 5.4.2
Intune SDK version 10.3.1

Summary

We are trying to integrate Microsoft Intune with our Android app to make it MAM aware.  So far, we have integrated both MSAL and Intune SDK.

  1. The app is a public app available in Google play store.
  2. The app is a single identity app.
  3. App is registered in the entra console. An entry for the Android platform is added as well along with the redirect URL. 
  4. In the Entra console, necessary API permissions are granted for the user, including the permissions that need to be granted by the admin is there for the user who tried to login into the app.

Integrated MSAL SDK with the app. When trying to login/acquire a token with MSAL, the app is requesting the following scopes.

val MSAL_SCOPES = arrayOf("https://graph.microsoft.com/User.Read", "https://msmamservice.api.application/DeviceManagementManagedApps.ReadWrite")

However, we are seeing that onError method of AuthenticationCallback is getting called with following error

AADSTS650052: The app is trying to access a service '<some_service_id>'(Microsoft Mobile Application Management) that your organization '<organization_id>' lacks a service principal for. Contact your IT Admin to review the configuration of your service subscriptions or consent to the application in order to create the required service principal. Trace ID: dbc0de90-49d8-4359-95b7-5dd023294501 Correlation ID: 288e25af-3ef0-4e3d-9c08-f42f494e454b Timestamp: 2024-08-09 10:39:49Z

We did some research and did not find a way to assign a Service Principal for MAM anywhere in both the Entra or Intune admin console. Such a step was not mentioned in Intune documentation as well. Any idea why this error is returning?

On a side note, in the sample app bundled with the Intune SDK, the second scope is not requested.  So, we tried the same by removing the second scope from the MSAL_SCOPES array above and then tried to login/acquire token. This time, we received the MSAL token. However, when we tried to register for MAM, we received a  different error.

val MSAL_SCOPES = arrayOf("https://graph.microsoft.com/User.Read")

Failed to get token for MAM Service AADSTS65001: The user or administrator has not consented to use the application with ID '<application_id>' named '<Our_app_name>'. Send an interactive authorization request for this user and resource. Trace ID: 329fb36f-1b87-45dc-ab3d-a3f1708c0f01 Correlation ID: 258b5140-c5b2-4317-9a77-ce3728d6c8b6 Timestamp: 2024-08-09 10:57:54Z

Other Details:

  1. App targets Android API 34
  2. Using Android Studio Koala | 2024.1.1
  3. Company portal app is installed.

Let me know if any other info is needed. I have attached some screenshots as well.
auth_config
entra_android_platform
entra_app_permissions
Any help is appreciated. 

@kanishkaBagga
Copy link

I am looking into this

@jayanth-quintet
Copy link
Author

Any update on this?

Also, I was also trying to find the documentation about the permissions that need to be given for Intune MAM to work with mobile apps. I found dedicated Entra documentation about how to grant permission. However, what I am looking for is a documentation on what permissions are needed specifically for Intune MAM to work in mobile apps.

@kanishkaBagga
Copy link

@jayanth-quintet , is this a multi-tenant application?

@jayanth-quintet
Copy link
Author

@kanishkaBagga Our app is a multi tenant application.

@kanishkaBagga
Copy link

@jayanth-quintet - The error AADSTS650052 you’re encountering indicates that your application is trying to access a service that your organization doesn’t have a service principal for. This typically happens in multi-tenant applications when the required service principal hasn’t been created or consented to by the tenant admin.
Here are some steps to resolve this issue:

  1. Admin Consent: Ensure that the tenant admin has granted consent for the application. You can do this by constructing an admin consent URL and having the admin navigate to it. The URL format is:
  2. https://login.microsoftonline.com/{tenant-id}/adminconsent?client_id={client-id}&redirect_uri={redirect-uri}
    Replace {tenant-id}, {client-id}, and {redirect-uri} with your tenant ID, client ID, and redirect URI respectively.
  3. Check API Permissions: Ensure that the API permissions required by your application are correctly configured in the Azure portal. Navigate to Azure Active Directory > App registrations > Your App > API permissions and verify that the necessary permissions are listed.
  4. KnownClientApplications: If your application is a multi-tier application, ensure that the knownClientApplications parameter is set in the app manifest. This parameter should include the client IDs of the applications that need to access the API.
  5. Tenant-Specific Endpoint: : Instead of using the common endpoint, use the tenant-specific endpoint for authorization. This can sometimes resolve issues related to multi-tenant applications.

@jayanth-quintet
Copy link
Author

@kanishkaBagga Thanks. Let me go through the above. I will get back to you.

@jayanth-quintet
Copy link
Author

@kanishkaBagga While I look into other points you mentioned in your comment, this is about the third point

Check API Permissions: Ensure that the API permissions required by your application are correctly configured in the Azure portal. Navigate to Azure Active Directory > App registrations > Your App > API permissions and verify that the necessary permissions are listed.

We assume the permissions are already provided. Reattaching the screenshot from the first message in this thread.

permissions

Do you think I need to grant any other permission for getting Intune MAM to work with Android application? I am still having difficulties finding a documentation that mentions about permissions in the context of getting Intune MAM to work.

@kanishkaBagga
Copy link

Please find the link here - https://learn.microsoft.com/en-us/mem/intune/developer/app-sdk-get-started#give-your-app-access-to-the-intune-mobile-app-management-service ( It is already defined in your case ) Did you verify the above steps?

@jayanth-quintet
Copy link
Author

@kanishkaBagga Thanks for your reply.

_

KnownClientApplications: If your application is a multi-tier application, ensure that the knownClientApplications parameter is set in the app manifest. This parameter should include the client IDs of the applications that need to access the API.
_

Our's is a single tier application.

_

Tenant-Specific Endpoint: : Instead of using the common endpoint, use the tenant-specific endpoint for authorization. This can sometimes resolve issues related to multi-tenant applications.
_

During the development stage, we are working with a single tenant. In the auth_config.json file, we replaced tenant_id with the specific tenant_id.

{
  "client_id" : "<our_client_id>",
  "authorization_user_agent" : "DEFAULT",
  "redirect_uri" : "msauth://<package_name>/<our_key_hash>",
  "account_mode" : "SINGLE",
  "authorities" : [
    {
      "type": "AAD",
      "audience": {
        "type": "AzureADandPersonalMicrosoftAccount",
        "tenant_id": "<our_tenant_id>"
      }
    }
  ]
}

However, this didn't make any difference.

We assume, moving forward, we will need to move away from static config json file and dynamically configure the tenant details in code. But for now, we only have one tenant.

_

Admin Consent: Ensure that the tenant admin has granted consent for the application. You can do this by constructing an admin consent URL and having the admin navigate to it. The URL format is:
_

Will get back to you on this. Just waiting for the admin consent to be done.

@jayanth-quintet
Copy link
Author

@kanishkaBagga
Regarding your solution about granting admin consent

Admin Consent: Ensure that the tenant admin has granted consent for the application. You can do this by constructing an admin consent URL and having the admin navigate to it. The URL format is:

When the admin tried to do this, it took us to a screen where all the Permissions were listed with an Accept CTA button at the bottom (see screenshot). However, the Accept button is not doing anything when we click on it. It continued to load.

We used the developer option to see what is going on underneath and saw that the following error was displayed in the console.

Failed to launch 'msauth://code/msauth.<package_name>%3A%2F%2Fauth?admin_consent=True&tenant=<tenant_id>' because the scheme does not have a registered handler.

Any idea what is going on here? At least, we now know there is a permission there to be granted, but could you help out about this error?
permission_page

@kanishkaBagga
Copy link

@jayanth-quintet -
Make sure that the application that is supposed to handle the msauth scheme is installed on your device. This is often the Microsoft Authenticator app or a similar application.
Verify that the URL scheme is correctly registered in the application's manifest file. For Android, this would be in the AndroidManifest.xml file, and for iOS, it would be in the Info.plist file.
Ensure that the tenant admin has granted consent for the application. You can do this by constructing an admin consent URL and having the admin navigate to it. The URL format is typically:
https://login.microsoftonline.com/{tenant_id}/adminconsent?client_id={client_id}&state=12345&redirect_uri={redirect_uri}
Replace {tenant_id}, {client_id}, and {redirect_uri} with the appropriate values for your application.

@jayanth-quintet
Copy link
Author

@kanishkaBagga

Make sure that the application that is supposed to handle the msauth scheme is installed on your device. This is often the Microsoft Authenticator app or a similar application.

I am pretty sure that the organization admin had tried to grant consent for the application from his desktop web browser. And he ran into the error we have mentioned in my previous comment.

As far as the mobile app is concerned, we always had the Intune company portal app installed on the mobile device we used to test our Intune integration.

Verify that the URL scheme is correctly registered in the application's manifest file. For Android, this would be in the AndroidManifest.xml file, and for iOS, it would be in the Info.plist file.

This is what we had in the Android manifest file for the Android app. We assume this is what you meant.

<activity android:name="com.microsoft.identity.client.BrowserTabActivity"
    android:exported="true">
    <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="<our_app_package_name>"
            android:path="/<keystore_keyhash>"
            android:scheme="msauth" />
    </intent-filter>
</activity>

Ensure that the tenant admin has granted consent for the application. You can do this by constructing an admin consent URL and having the admin navigate to it. The URL format is typically:
https://login.microsoftonline.com/{tenant_id}/adminconsent?client_id={client_id}&state=12345&redirect_uri={redirect_uri}
Replace {tenant_id}, {client_id}, and {redirect_uri} with the appropriate values for your application.

As we mentioned in our previous comment, the admin was unable to grant consent. The Accept button seems to do nothing. Do you have any idea about what was happening there.

@kanishkaBagga
Copy link

is the URL looking like this - https://login.microsoftonline.com/<tenant_id>/adminconsent?client_id=<client_id>&redirect_uri=msauth.<package_name>://auth

@jayanth-quintet
Copy link
Author

@kanishkaBagga

is the URL looking like this - https://login.microsoftonline.com/<tenant_id>/adminconsent?client_id=<client_id>&redirect_uri=msauth.<package_name>://auth

For iOS, Yes.

For Android, it looked like below

https://login.microsoftonline.com/<tenant_id>/adminconsent?client_id=<client_id>&redirect_uri=msauth://<app_package_name>/

@jayanth-quintet
Copy link
Author

jayanth-quintet commented Oct 16, 2024

@kanishkaBagga
We have further updates on this. We have communicated with the support team in Microsoft Entra console and they have found out that the consent for all permissions we requested has been granted by the admin. They also asked us to add three API permissions for the app - offline-access, openid and profile. We have added them for the app in the Entra console. 

Permission

After this, we tried to login via MSAL from the app. We have played around with the following scopes again.

val MSAL_SCOPES = arrayOf("https://graph.microsoft.com/User.Read", "https://msmamservice.api.application/DeviceManagementManagedApps.ReadWrite")

val parameters = SignInParameters.builder()
            .withScopes(MSAL_SCOPES.toList())
            .withActivity(activity)
            .withCallback(authInteractiveCallback)
            .build()
mMsalClientApplication?.signIn(parameters)

private val authInteractiveCallback = object: AuthenticationCallback {        
        override fun onSuccess(authenticationResult: IAuthenticationResult?) {
            Log.e(MSAL_TAG, "onSuccess of authInteractiveCallback")
            authenticationResult?.let { result ->
                msalLog("account id ${result.account.id}")
                msalLog("account authority ${result.account.authority}")
                msalLog("account username ${result.account.username}")
                msalLog("account idToken ${result.account.idToken}")
                msalLog("account tenantId ${result.account.tenantId}")
                msalLog("result tenantId ${result.tenantId}")
                msalLog("result scope ${result.scope}")
                msalLog("result expiresOn ${result.expiresOn}")
                msalLog("result accessToken ${result.accessToken}")
                msalLog("result authenticationScheme ${result.authenticationScheme}")
                msalLog("result authorizationHeader ${result.authorizationHeader}")
                msalLog("result correlationId ${result.correlationId}")
           }
        }

        override fun onError(exception: MsalException?) {
            msalLog("onError of authInteractiveCallback")
            msalLog(exception?.localizedMessage ?: "excemption Null")
            if (exception is MsalDeclinedScopeException) {
                msalLog("Declined scopes : ${exception.declinedScopes?.toString() ?: ""}")
                msalLog("Granted scopes : ${exception.grantedScopes?.toString() ?: ""}")
            }
            exception?.printStackTrace()
        }

        override fun onCancel() {
            msalLog("onCancel of authInteractiveCallback")
        }
    }

Case 1: When we tried with both the scopes mentioned above

When we used both the scopes when trying to login, the Microsoft login screen showed up, but after signing in, the onError callback got called with the exception of type MsalDeclinedScopeException. When we tried to print the declined and granted scopes from this exception, we found that 

Declined Scopes https://graph.microsoft.com/user.read
Granted Scope https://msmamservice.api.application/DeviceManagementManagedApps.ReadWrite

For some reason the user.read graph API permission is getting declined when I include the DeviceManagementManagedApps.ReadWrite permission. 

Case 2: When we tried login with only the Graph API User.Read permission

val MSAL_SCOPES = arrayOf("https://graph.microsoft.com/User.Read")
When we removed the second permission and tried login again, the login was successful. We received the onSuccess authentication callback with the correct account details. However, when we tried to register for MAM using the Intune SDK using the registerAccountForMAM call, we received a MAM_ENROLLMENT_RESULT notification with NOT_LICENSED error.

val mgr = MAMComponents.get(MAMEnrollmentManager::class.java)
        mgr?.registerAccountForMAM(
            account.username, //upn
            account.id, //aadid
            account.tenantId, //tenantID
            account.authority //authority
        )

//logsReceived MAMEnrollmentNotification:  MAM_ENROLLMENT_RESULT
notif.enrollmentResult.name:  NOT_LICENSED
notif.error?.name:  NONE_KNOWN
notif.scenario?.name:  ENROLLMENT
notif.enrollmentResult?.code:  1

Basically we are kind of confused. If we add the permission DeviceManagementManagedApps.ReadWrite in the scope, that permission is getting accepted, but the graph API permission User.Read getting declined. However, if we remove the DeviceManagementManagedApps.ReadWrite permission, the graph API permission is getting accepted.

We have used the Send logs feature in Company Portal APP and the incident ID that is shown there is YTJDDR42. Does this help you to get the logs for this issue?

On a side note, do we really need the https://msmamservice.api.application/DeviceManagementManagedApps.ReadWrite permission in the scope for registering and working with MAM? We are asking because the sample TaskR app coming with the SDK doesn't add this.
 
Let us know. 

@kanishkaBagga
Copy link

@jayanth-quintet yes this would help , I am checking the logs based on your incident id

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

2 participants