Unable to access Microsoft Graph API's - microsoft-teams

I am unable to access Microsoft Graph API's, I am getting the below error object-
{
"error": {
"code": "Authorization_RequestDenied",
"message": "Insufficient privileges to complete the operation.",
"innerError": {
"date": "2021-03-11T07:17:41",
"request-id": "fa7c7d27-50f3-46ca-b7a9-25198e6cdd8e",
"client-request-id": "fa7c7d27-50f3-46ca-b7a9-25198e6cdd8e"
}
}
}
I have registered the application in the Azure registration portal, acquired client_id, tenant, and client_secret, and used that to generate an access token with the help of the below API-
POST https://login.microsoftonline.com/{tenant}/oauth2/v2.0/token
Host: login.microsoftonline.com
Content-Type: application/x-www-form-urlencoded
client_id={client_Id}
&scope=https%3A%2F%2Fgraph.microsoft.com%2F.default
&client_secret={client_secret}
&grant_type=client_credentials
The access token which I got in this response is used to further call Graph API's but it's giving me an error object attached above.
Please help me here.

This particular error is typically thrown when your application does not have the required permission to call a particular endpoint. Please go to the azure portal and grant the necessary Graph permissions for the endpoints you are calling. You can view the particular permissions you need by going to the Microsoft Graph documentation of the API you want to call and check under the permissions section. For signed in users, you will need the delegated permissions and for access as an application/daemon, you will need application permissions.
To grant these permissions, follow these steps:
Azure portal > Azure Active Directory > App Registration > All Applications > Search with your ClientID/AppID.
In that application navigate to:
Api Permissions > Add a permission > Microsoft Graph > Delegated permissions > Expand User > Select required permissions.
Once the permissions are added, click on Grant Admin Consent for Your Tenant.

Related

Token retrieval error after changing password

We are using Azure AD B2C Custom policies with Microsoft Azure Active Directory to authenticate users. We implemented the password change policy as given in the example below.
https://github.com/Azure-Samples/active-directory-b2c-custom-policy-starterpack/tree/main/scenarios/password-change
We created a link the user can visit and change his password. Once the password is changed, the user is redirected to the application again.
However, in some cases, we get the following error when the user is redirected to the application after changing the password.
{
"error": "invalid_grant",
"error_description": "AADB2C90088: The provided grant has not been issued for this endpoint. Actual Value : B2C_1A_Dev_SignupSignin and Expected Value : B2C_1A_Dev_PasswordChange\r\nCorrelation ID: b3a2fdd5-df58-4aa1-8eca-d91503ebb75a\r\nTimestamp: 2022-08-31 12:23:48Z\r\n"
}
This error does not happen to all users. But for some users, it happens always.
We use MSAL Angular library with the following versions.
azure/msal-angular": "^2.1.1"
azure/msal-browser": "^2.22.0"
We appreciate any help to resolve this issue.

Google Admin SDK with service account without impersonation

The goal is to establish a Service Account in the G-Suite platform that an application can use to perform actions without prompting users to authenticate.
We are experiencing issues very similar to the following postings, but slightly differently.
Google Admin SDK authentication with service account
How to authorise a service account to access the Google Admin API
As long as we follow the 'impersonation" flow, things work. With impersonation, the authorization rules follow the user being impersonated. Ideally, we want to SCOPE the service account accordingly and not impersonate a user. When we do this, we constantly receive a 403.
We've tried our best to follow the instructions here:
https://developers.google.com/admin-sdk/directory/v1/guides/delegation
https://developers.google.com/identity/protocols/OAuth2ServiceAccount?hl=en_US#delegatingauthority
https://medium.com/#Skaaptjop/access-gsuite-apis-on-your-domain-using-a-service-account-e2a8dbda287c
Our Java snippet is similar to this:
final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
File file = new File(MdmResource.class.getClassLoader().getResource("myproject.p12").getFile());
GoogleCredential credential = new GoogleCredential.Builder()
.setTransport(HTTP_TRANSPORT)
.setJsonFactory(JSON_FACTORY)
.setServiceAccountId("105601508644514129999")
.setServiceAccountPrivateKeyFromP12File(file)
.setServiceAccountScopes(
Collections.singletonList(DirectoryScopes.ADMIN_DIRECTORY_USER_READONLY))
.setServiceAccountUser("user#domain.com") // 403 when this is commented out
.build();
Directory dir = new Directory(HTTP_TRANSPORT, JSON_FACTORY, credential);
Get result = dir.users().get("dude#domain.com");
User user = result.execute();
System.out.println(user.get("customerId"));
In GCP, we created the ServiceAccount while logged in as a superadmin. We enabled Domain-Wide delegation and generated the keys (in this example, the p12 type and used the corresponding file as input into the Java app).
Then, in the API Library, we enabled Admin SDK.
In the Google Admin, under Security/Advanced settings, we setup the scopes. We used 105601508644514129999 and https://www.googleapis.com/auth/admin.directory.device.mobile,https://www.googleapis.com/auth/admin.directory.user.readonly,https://www.googleapis.com/auth/admin.directory.user
When we run the Java code, we see the following when "setServiceAccountUser" is commented out (works fine when impersonating, as long as the user has the right permissions):
{
"code" : 403,
"errors" : [ {
"domain" : "global",
"message" : "Not Authorized to access this resource/api",
"reason" : "forbidden"
} ],
"message" : "Not Authorized to access this resource/api"
}
So, it seems like our SA is not correctly connected to scopes, but I'm out of ideas how to do this.
BTW, the 105601508644514129999 is the SA Unique ID and Client ID of the OAuth 2.0 credentials that were automatically generated during the SA creation process. We also used the SA Email for the "setServiceAccountId" as shown in the following example, but still getting 403. https://developers.google.com/admin-sdk/directory/v1/guides/delegation. Actually, I think this example has another issue with .setServiceAccountScopes too.
Finally...
<dependency>
<groupId>com.google.auth</groupId>
<artifactId>google-auth-library-oauth2-http</artifactId>
<version>0.20.0</version>
</dependency>
<!-- Used to navigate Google Directory services, like https://developers.google.com/admin-sdk/directory -->
<dependency>
<groupId>com.google.apis</groupId>
<artifactId>google-api-services-admin-directory</artifactId>
<version>directory_v1-rev117-1.25.0</version>
</dependency>
Any thoughts?
Service accounts are not in the G Suite domain (even if they are owned by a user / project in it) and thus cannot be granted admin access to the G Suite domain. All they can do is impersonate users in the domain with Domain-Wide Delegation.
What you likely want to settle on is granting regular OAuth as an admin user using a client ID and secret and being sure to get a long-lived refresh token access_type=offline. This will allow you to refresh the access token whenever it expires and continue acting as the single admin user as long as they don't revoke your access.

How to authorise a service account to access the Google Admin API

We are trying to create an integration with the Google Admin SDK in order to be able to retrieve, update and create accounts within our domain. However, we keep receiving a 403 error indicating that we are not authorized to access the resource/api.
We are using the credentials obtained from a service account which has Domain-wide Delegation of Authority enabled and the following two scopes:
https://www.googleapis.com/auth/admin.directory.user.readonly, https://www.googleapis.com/auth/admin.directory.user. We are generating the JWT (which also includes these two scopes) and then sending a request to https://www.googleapis.com/oauth2/v4/token to retrieve the access token.
We are then using the access token to send a request to https://www.googleapis.com/admin/directory/v1/users?domain=XXXX.com. We are including the access token as a Bearer token, part of the headers.
In the response we are getting the following message:
{
"error": {
"errors": [
{
"domain": "global",
"reason": "forbidden",
"message": "Not Authorized to access this resource/api"
}
],
"code": 403,
"message": "Not Authorized to access this resource/api"
}
}
Is it possible to clarify what are we doing incorrectly?
The problem was that the JWT must include the sub field: The email address of the user for which the application is requesting delegated access.
In order for this to work you must set up domain wide delegation by doing this your service account will then have access to the data in question.
Locate the newly-created service account in the table. Under Actions, click more_vert then Edit.
In the service account details, click expand_more Show domain-wide delegation, then ensure the Enable G Suite Domain-wide Delegation checkbox is checked.
If you haven't yet configured your app's OAuth consent screen, you must do so before you can enable domain-wide delegation. Follow the on-screen instructions to configure the OAuth consent screen, then repeat the above steps and re-check the checkbox.
Click Save to update the service account, and return to the table of service accounts. A new column, Domain-wide delegation, can be seen. Click View Client ID, to obtain and make a note of the client ID.

How to debug Authentication configuration?

We are experiencing problems with Authentication of Service Accounts for domain-wide delegation.
The main problem is it's hard to investigate and debug the auth configuration so
we would like to ask for some tips how to debug the configuration.
Or maybe we are missing some configuration options and you can point us to them.
Our process is:
Create SA(=Service Account) with enabled domain-wide delegation.
Authenticate SA in GSuite admin console(https://support.google.com/a/answer/162106?hl=en).
use client_id from the credentials file. (now email)
scopes are comma-separated without spaces between.
Ensure the "Security > API Reference > API Reference -> 'Enable API Access'" is checked.
For some GSuite domains this is working configuration, but we got some domains where this configuration results in:
google.auth.exceptions.RefreshError: ('unauthorized_client: Client is unauthorized to retrieve access tokens using this method.', '{\n "error": "unauthorized_client",\n "error_description": "Client is unauthorized to retrieve access tokens using this method."\n}')
In our understanding, this is the error saying the client_id and scopes were not added to the "Manage API client access" page. (=List of authenticated clients)
We really ensured that the GSuite domain we are requesting has the proper client_id and scopes added in the list of authenticated clients + has the 'Enabled API Access'.
We even created Shared Desktop with them and did it by ourselves to be fully sure of it.
But the error still persists.
However, we are not able to replicate this problem on our test GSuite domain.
We tried couple of options using same SA as the client:
The impersonated account hasn't permissions to access the resource.
This result in:
googleapiclient.errors.HttpError: https://www.googleapis.com/admin/directory/v1/users?customer=my_customer&alt=json returned "Not Authorized to access this resource/api">
The scopes are just partial:
google.auth.exceptions.RefreshError: ('access_denied: Requested client not authorized.', '{\n "error": "access_denied",\n "error_description": "Requested client not authorized."\n}')
The 'Enabled API Access' is not checked.
googleapiclient.errors.HttpError: https://www.googleapis.com/admin/directory/v1/users?customer=my_customer&alt=json returned "Domain cannot use apis.">
The error we are receiving from the client("Client is unauthorized to retrieve access tokens using this method."), we are able to replicate only if the client_id is not in the list of authenticated clients at all.
But we are sure, the problematic GSuite domains have the SA authenticated in "Manage API client access" page.
We are using these scopes: https://www.googleapis.com/auth/userinfo.profile,https://www.googleapis.com/auth/userinfo.email,https://www.googleapis.com/auth/gmail.readonly,https://www.googleapis.com/auth/plus.login,https://www.googleapis.com/auth/calendar.readonly,https://www.googleapis.com/auth/contacts.readonly, https://www.googleapis.com/auth/admin.directory.user.readonly
Do you have any ideas how to debug/solve this issue?
Here is what you need to do. Double check each step. If in doubt, start over.
Enable "Admin SDK API. This is enabled on a per project basis.
Create a service account. Do not add or remove any privileges. Don't change the service account in any way. If you do you will get an error that you are not authorized.
Enable Domain-wide Delegation on the service account.
Follow this document to delegate domain-wide authority to your service account:
Delegate domain-wide authority to your service account
When creating the service account credentials (from the downloaded Json) you will need the following scopes for full G Suite management:
"https://www.googleapis.com/auth/admin.directory.group",
"https://www.googleapis.com/auth/admin.directory.user"
Impersonate a user account which creates new credentials. The user account needs to be a G Suite superadmin. This account must have logged into G Suite at least once and accepted the Terms of Service.
Create your client using the credentials from step #5.
Working Python Example:
from googleapiclient.discovery import build
from google.oauth2 import service_account
# This is the service account credentials file
credentials_file = 'google-directory-api.json'
# In this example I only need to send email
credentials = service_account.Credentials.from_service_account_file(
credentials_file,
scopes=['https://www.googleapis.com/auth/gmail.send'])
# This user is a G Suite superadmin
impersonate = 'username#example.com'
credentials = credentials.with_subject(impersonate)
service = build('gmail', 'v1', credentials=credentials)
I think we are going to need to take this in stages. Lets start with your first error and see if that fixes your issue.
Background info
There are several types of clients that you can create in Google developer console. Here are the top three.
Browser client: Used for web applications
Native client (other): used for installed desktop applications
Service account: used for server to server communication.
The clients are different the client.json file you download is different and the code used to authenticated to the authentication server is also different.
Error 1: code / client missmatch
unauthorized_client: Client is unauthorized to retrieve access tokens using this method.
Can mean one of two things. Either you have created a service account client and you are not using service account code to authenticate or you are are using the code to authenticate with a service account but you have not created a service account client. You haven't posted what language you are using or any code so I cant tell you if the code you are using is intended to be used with a service account or not. Your going to have to look into this one a bit.
Check in developer console make sure your client is like this If it is check your code. If it isnt then create a real service account client and try again.

Insert User in Google Directory with Service Account

I wrote a PHP application which tries to create an User in my Google Directory. I don't use the Google Libraries. I succeded making requests to the Android Enterprise API. I can enroll and unenroll Enterprise Service Accounts with my MSA. So I assume my Code for the JWT and Requests work.
I created a Service Account and enabled "Domain Wide Delegation" and added the following permission "https://www.googleapis.com/auth/admin.directory.user, https://www.googleapis.com/auth/admin.directory.group" to my API Client under the "Manage API client access" windows.
My Service Account has the status role "Editor" in the "Permissions for project" windows.
So first my script gets the Bearer token from the Google Server, for that I create a JWT and encrypt it with my private key.
The Token contains the following fields
"iss" => sacname#projectname.iam.gserviceaccount.com
"scope" => "https://www.googleapis.com/auth/admin.directory.user, https://www.googleapis.com/auth/admin.directory.group"
"aud" => "https://www.googleapis.com/oauth2/v4/token",
"exp" => timestamp+3000,
"iat" => timestamp
When I do that request I get a bearer token, but when I use that token to make the insert request I always get the message "Not Authorized to access this resource/api" with an HTTP 403.
When I add the field "sub" to my JWT and specify the email of the Project admin "admin#mydomain.com" I can't even get the bearer token, then I get a 401 error with the following message "Unauthorized client or scope in request."
After that I tried something "easy", I just wanted to get a list of all users in my directory. But the Google Server just reponds with an "bad request" error. I got the same error with the API Explorer which is on API Page. Maybe the API is broken ? At least the API Explorer should work.
https://developers.google.com/admin-sdk/directory/v1/reference/users/list
Do you have some ideas why I can't create users with my service account ?
(I had to insert some spaces in the scopes and urls because I'm not allowed to post more than two links)
Greetings
Philip
Adding the sub claim is the right thing to do, because you must impersonate a super admin to use Directory API. If you get a "Unauthorized client or scope in request" response, that might be because there's a typo in the service account client ID you used to authorize (or the scopes), or that not enough time has passed (it usually propagates within a few minutes, but could take up to 24 hours).
See JWT error codes for more details on possible errors and causes.
Do you have some ideas why I can't create users with my service account?
Yes. Your service account seems to have no authority to create users. Check your Service Account's role in GDC to check if it's Owner, Editor, Viewer,etc. The scope of what they can do depends on that. Watch this Google video for a live demo.
Also, try to read more on Using OAuth 2.0 for Server to Server Applications.

Resources