Check if users deleted in clients Azure AD - azure

I am integrating Login with Azure AD for one of my clients on my website. I am only targeting one specific group in their organisation, and not everybody in the entire organisation.
This new feature has 2 requirements:
We need to create an account for people logging in via their email using our clients Azure AD.
We need to run a CRON job daily to check if anybody has been removed in their AD (due to them leaving the company), so we also need to remove their profile in our application.
For number 1, I think it's sufficient to call the /authorization, /token and /userinfo endpoints. Is this correct?
But for number 2, I am having issues to see how this is possible.
When browsing the graph explorer (https://developer.microsoft.com/en-us/graph/graph-explorer) I can find the following 2 API methods:
GET all users in the organization /users ---> But i am unsure whether this returns all the users in their AD, or only the ones applicable for my application?
GET direct members of a group with count /groups/<id</members ---> Is this the one I am looking for when they are assigned into a specific group?
I've also found this SO link : https://stackoverflow.com/a/64553305 which talks about saving the access token and refresh token. Is it possible if I save these two to fetch the userinfo at any point in time? This way I could possibly query all the created accounts each day and if one of them returns a status deleted, or empty I know the account no longer exists? Or is this not an option?
Thanks in advance!
UPDATE:
I noticed that my client granted me the User.Read and User.Read.All graph permissions.
But i'm not certain how to call this API? When calling this API in Postman :
https://graph.microsoft.com/v1.0/users/123-this-is-the-id
I am getting the following response:
{
"error": {
"code": "InvalidAuthenticationToken",
"message": "Access token is empty.",
"innerError": {
"date": "2021-10-07T12:59:05",
"request-id": "...",
"client-request-id": "..."
}
}
}

Related

How to get access token for subscription in a different tenant?

I'm trying to use "invoke an http request" action in power automate to query a log analytics workspace. I have access to perform this from azure portal. I referred this Microsoft article to get the URI. But when I try to execute the flow, I get the below error:
Complete error message:
{
"error": {
"message": "The provided authentication is not valid for this resource",
"code": "InvalidTokenError",
"correlationId": "45e0ff0c-01f1-4ea5-a11d-ec6ce2d71b8b",
"innererror": {
"code": "InvalidAuthenticationTokenTenant",
"message": "The access token is from the wrong issuer 'https://sts.windows.net/687f51c3-0c5d-4905-84f8-97c683a5b9d1/'. It must match one of the tenants 'https://sts.windows.net/2f4a9838-26b7-47ee-be60-ccc1fdec5953/,https://sts.windows.net/a6eb2ff5-3009-4bfc-b769-24a2f82c1913/' associated with this subscription. Please use any authority (URL) from 'https://login.windows.net/2f4a9838-26b7-47ee-be60-ccc1fdec5953,https://login.windows.net/a6eb2ff5-3009-4bfc-b769-24a2f82c1913' to get the token. Note, if the subscription is transferred to another tenant there is no impact to the services, but information about new tenant could take time to propagate (up to an hour). If you just transferred your subscription and see this error message, please try back later."
}
}
}
The analytics workspace that I'm trying to query is not under my AAD tenant. It is under another tenant/directory, which I have access from portal. How can I get the access token so that I can execute this query?
I have already tried the action "Run query and list results" in power automate, which gave the same error.
Any suggestions?
Please check below points:
Please check if you have multiple subscription .So while
requesting access token , it is the tenant which is not part of the
subscription that you might have selected. In such a case try to
change the settings and make your subscription map to the directory
which you want to use.
In some cases browser tries or attempts to get an access token from
already logged in tenant .So If its under same subscription, try to
check after clearing the cache
You can also put required tenant ID in the enviroment settings of
your particular app, using DefaultAzureCredential()
Or Configure the authority defining the tenantId
https://login.microsoftonline.com/{tenant-id} for multiple tenants
Signing in once to access to all the Azure Log Analytics data from
all tenant may not be feasible.It may require reauthentication .
Check this way to get
the accesss token for that particular tenant Request an
authorization token - Azure Monitor | Microsoft Docs and use the
token to call the log analytics workspace
References:
Query - Execute - REST API (Azure Log Analytics) | Microsoft Docs
azure log analytics - Valid authentication was not provided - Stack
Overflow

"User not found" for Graph API request in the Azure enterprise app security group with client credentials auth flow

Design
Goal
Get calendar events for a given user.
Requirements
Application should have access to the MS Graph API.
Application should act like a daemon/background process and not depend on user's login.
Application should have access to the minimal number of users' data in the Azure Active Directory (AAD).
Application should be able to fetch user's calendar events and create them.
Implementation / Setup
to fulfill (1) Azure (Enterprise) App was created as described here.
to enable (2) client credentials flow was used with the setup of application permissions
to meet (3) a security group - as described here - was created with a limited number of users with the related policy that included related permissions (see here). The group was later connected to the app following this instruction.
to implement (4) the Calendar.Read and Calendar.ReadWrite as required by the actions here and here were added to the policy mentioned in the previous setup step.
Testing
Two HTTP requests were used: one to get the token and another to read events.
token request from the Identity Platform
curl --location --request POST 'https://login.microsoftonline.com/<TENANT_ID>/oauth2/v2.0/token' \
--data-raw 'client_id=<APPLICATION_TOKEN>&scope=https%3A%2F%2Fgraph.microsoft.com%2F.default&client_secret=<APPLICATION_SECRET>&grant_type=client_credentials'
Upon inspection of the token here I see that it contains required permissions:
"roles": [
"Calendars.Read",
"Calendars.ReadWrite"
]
fetch request of the calendar events from Graph API
curl --location --request GET 'https://graph.microsoft.com/v1.0/users/<USER_ID>/calendar/events' \
--header 'Authorization: Bearer <TOKEN>'
results in the following error:
{
"error": {
"code": "ResourceNotFound",
"message": "User not found",
"innerError": {
"date": "2022-02-08T08:25:39",
"request-id": "bfaca1f9-e79b-491c-8d75-5a62317e299b",
"client-request-id": "bfaca1f9-e79b-491c-8d75-5a62317e299b"
}
}
}
The user id is from my account that I found in the Azure Active Directory details of the Azure Tenant. I double-checked that after adding other users.
Before-asking investigation
This issue looks closest to my case as it uses the client credentials auth flow. But it uses global permissions for all users in the AAD, while we use more fine-grained approach with a security group. It also shows a different error "Resource could not be discovered." versus "User not found" in my case.
In order to call /{user-id}/calendar/events to work the user must have mailbox on Exchange Online if you are using client credentials for Daemon applications.
Also, It seems assigning license to a guest account (Personal account in this case) is not possible and hence the user account never gets access to the calendar service (part of o365 exchange online) due to which it cannot retrieve the calendar information of personal account.
Please refer my answer similar to this in Q&A for detailed description.
Short Version
I was missing the application permissions and assumed that they are assigned on the level of security group. Only restriction happen on that level.
Long Version
The updated mental model looks like this:
It means that the application permissions for MS Graph API are required.
The security group is only restricting / limiting the access to the users mentioned in the policy.

Not able to get findMeetingTimes using Microsoft Graph API

I am trying to get and analyze data from office 365 resource room booking data, for that I am using graph API to find meeting times,
https://graph.microsoft.com/v1.0/me/findMeetingTimes ,
this query perfectly working on Microsoft graph explorer after given permissions to calendar.ReadWrite and calendar.ReadWrite.Shared, but this is not working through api call in SharePoint page and postman test with same permissions given in azure WEB API.
it is returning below error
{
"error": {
"code": "ErrorAccessDenied",
"message": "Access is denied. Check credentials and try again.",
"innerError": {
"request-id": "90f335e7-1955-48c2-a9e9-300ea232e181",
"date": "2018-10-26T07:47:13"
}
}
}
If any suggestion appreciated.
I'm assuming you are using the MSGraphClient inside of SPFx, it is using the delegated permissions (not app permissions as per the comment in this thread). Can you confirm you are using this? https://learn.microsoft.com/en-us/sharepoint/dev/spfx/use-msgraph
This api (https://developer.microsoft.com/en-us/graph/docs/api-reference/v1.0/api/user_findmeetingtimes) requires "Calendars.Read.Shared, Calendars.ReadWrite.Shared" as you stated.
You would need to add additional permissions for this api call to work. As you only get User.Read.All for SPFx with MSGraphClient. This is documented here https://learn.microsoft.com/en-us/sharepoint/dev/spfx/use-aadhttpclient
From your provided request Id, I can see that your request had these scopes, which is missing the Calendars.Read.Shared permissions scope.
"Mail.ReadWrite","User.ReadWrite.All","Calendars.Read","People.Read.All","Group.Read.All","Directory.ReadWrite.All","MailboxSettings.Read","Contacts.ReadWrite","Group.ReadWrite.All","Sites.Manage.All","User.Invite.All","Files.ReadWrite.All","Directory.Read.All","User.Read.All","Files.Read.All","Mail.Read","Calendars.ReadWrite","Mail.Send","MailboxSettings.ReadWrite","Contacts.Read","Sites.FullControl.All","Reports.Read.All"
Look into the permissions of findMeetingTimes. You mode of authentication could be the root cause. For me I was tryint to use Application mode and this is not supported in this API.
I used and alternative api, /calendar/getSchedule to achieve this. If you login as your userid use ME option or use application mode login to login and use {id|userPrincipalName} to get calendar details for any meeting room.
Refer: https://learn.microsoft.com/en-us/graph/api/calendar-getschedule?view=graph-rest-1.0&tabs=http
Graph API Explorer link below provides the basics on how to login and got good examples for Graph to begin with.
https://developer.microsoft.com/en-us/graph/graph-explorer

calling microsoft graph api via another rest service

Good day!
We need a calendar facility for the project that we're working in right now. For some reason, we are limited to using the Office 365 calendar or the outlook calendar. We stumbled upon the Microsoft Graph APIs which seems to be the right tool to fulfill what we want to do. So the idea is to create a Microsoft account which will be used as the main calendar where our wrapper(wrap the microsoft graph API calls) API can pull events from and eventually disseminate to client requests.
So here is what we've done so far:
Created a Microsoft account with the domain of #outlook.com
Plotted some calendar events using the said Microsoft account
Tried to follow this guide from the Microsoft site.
We agreed to create a wrapper API which will call the Microsoft Graph APIs but before this we tried to access the said APIs via postman. The problem is that postman cannot get any response from the endpoint of the /authorize API which is need to gain an access token to finally call the respective Microsoft graph APIs.
Now we do not know if we are trying to attack this wrongly or whatever. Do you have any idea what we are missing here? Thanks in advance and I hope someone can shed light in this matter.
UPDATE:
We were able to have some progress. After some time, we bumped in the azure active directory portal. We are now able to get an access token using this URL.
https://login.microsoftonline.com/<directory-id>/oauth2/token
Now when we are accessing the actual MS Graph API endpoint that we are supposed to call, we are receiving a 401 Unauthorized response even though we are using the obtained token from the previous API call. This is the URL that we are trying to get a response:
https://graph.microsoft.com/v1.0/me/calendar/calendarView?startDateTime=2018-08-01T00:00:00.0000000&endDateTime=2018-08-31T23:59:59.0000000
This is all being done via postman first.
UPDATE:
We tried to grant every permission possible in the Azure Active Directory portal and confirmed the consent at
https://login.microsoftonline.com/<domain>.onmicrosoft.com/adminconsent?client_id=<client-id>
but unfortunately we're still hitting the 401 Unauthorized wall. In Microsoft Graph Explorer, everything is working fine. So what could be missing in our postman implementation that MS Graph Explorer is doing implicitly? Thanks in advance for any help!
UPDATE
After further reading, we've found out some important details. First, we've found out that there are two sets of APIs from Microsoft. One is the Azure Active Directory API and the other is the Microsoft Graph API. Both APIs use the same URL to get access tokens by using client credentials. Below is the URL:
https://login.microsoftonline.com/<directory-id>/oauth2/v2.0/token
Substitute the with your personal data from azure portal. Using this URL to get an access token, you need to supply some data in the request body.
client_id - client id of registered application in azure portal
client_secret - secret key of registered application in azure portal
grant_type - 'client_credentials' --> meaning you'll get an access token by using client credentials
scope - 'https://graph.microsoft.com/.default' or 'https://graph.windows.net/.default' --> this controls which API are you going to access. The first one is to access Microsoft Graph API and the other is to access Azure Active Directory API.
We are now able to get an access token and use it to access the actual API that we need. Below is the URL of the said API:
https://graph.microsoft.com/v1.0/users/<azure-tenant-name>.onmicrosoft.com/calendar/calendarView?startDateTime=2018-08-01T00:00:00.0000000&endDateTime=2018-08-31T23:59:59.0000000
Notice that the URL does not use /me because upon reading using it required a signed in user. Unfortunately we are still getting the 401 Unauthorized error but the errors did change now. We are getting to errors intermittently. Sometimes the API call would return one or the other alternately. Below are the return of the API calls.
{
"error": {
"code": "InvalidTenant",
"message": "The tenant for tenant guid '<directory-id-goes-here>' does not exist.",
"innerError": {
"request-id": "<some-request-id>",
"date": "2018-08-22T04:29:27"
}
}
}
{
"error": {
"code": "UnknownError",
"message": "",
"innerError": {
"request-id": "<some-request-id>",
"date": "2018-08-22T04:54:11"
}
}
}
We feel we've moved a step forward. We're still not getting what we need though. Now the mystery are these 2 API call responses. What could be the reason of this? Thanks in advance for anybody's help
UPDATE
Upon even further reading we've discovered that there are authentication flows to get an access token. Depending on the API that you want to call, some authentication flows will not work on it because they need more details and security to execute themselves. So we've tried:
Client Credential Grant
Resource Owner Credential Grant
Authorize Code Grant
But still, unfortunately, we are still stuck in the previous error. We are getting 401 Unauthorized and the response payload is either InvalidTenant or UnknownError.
I just went through a similar problem yesterday, the 401 Unauthorized error.
I was trying to access the calendar of an employee via Microsoft's Graph API, but I was receiving the same response as you.
Resquest:
https://graph.microsoft.com/v1.0/users/employee-email/calendarview?startdatetime=2018-10-21T00:00:00Z&enddatetime=2018-10-27T23:59:59Z&$select=subject,categories,start,end,sensitivity
Response:
{
"error": {
"code": "UnknownError",
"message": "",
"innerError": {
"request-id": "<request-id>",
"date": "<date>"
}
}
}
Then I decided to check if had the Office 365. He didn't. I'm just a developer, so I ask the guys from infrastructure to install Office 365 on the empleyee's machine, or add him to an enterprice account, or something like that.
After they finished, the requests to his calendar worked just fine :)

"Access Token missing or malformed" error while accessing Azure AD Graph API

I have an account on Azure where we run various applications in docker containers.
I would like to connect to Active Directory on this account and be able to manage various aspects such as creating new users, etc.
I found following API browser:
https://learn.microsoft.com/en-us/rest/api/graphrbac/users/list
Unfortunately when I log in as a user with admin rights (Global Administrator) and provide tenant ID, when I call users/list endpoint, I get following error with 401 status:
{
"odata.error": {
"code": "Authentication_MissingOrMalformed",
"message": {
"lang": "en",
"value": "Access Token missing or malformed."
},
"date": "2018-07-20T14:01:24",
"requestId": "9f070c46-a949-41bf-85c9-f1ccf97975db",
"values": null
}
}
What is interesting - if I use any other random endpoint, for example: https://learn.microsoft.com/en-us/rest/api/servermanagement/node/list - it works fine. In this case it returns empty set, but at least it doesn't fail with strange authentication error.
I also can reproduce the issue that you metioned if I test Users - List Rest API directly from the site.
https://learn.microsoft.com/en-us/rest/api/graphrbac/Users/List
According to exception, the root cause of the issue is token audience. You could check the actual access token in the JWT.io.
You could get that the audience is https://management.core.windows.net/. The token that is acquired will work for other Azure Services like webapps, compute, ResourceManager, etc. but not for Graph.
You could test it with Azue AD graph explorer, then it will work for you.
The audience should be https://graph.windows.net

Resources