Listing PrincipleIDs eligible for Global Admin role with Graph API - microsoft-graph-api

I know that this will give me active role assignments
$uri = "https://graph.microsoft.com/v1.0/directoryRoles/62e90394-69f5-4237-9190-012177145e10/members"
$Role = Invoke-RestMethod -Uri $Uri -Headers $Header -Method get -ContentType "application/json"
$Role.value.displayname
but how do I get eligible role assignments? the only thing I can find is requests to PIM-up but nothing that shows me what users have the ability to PIM-up for a specific role.

Here is the API to get the List the directory roles that are activated in the tenant
GET https://graph.microsoft.com/v1.0/directoryRoles
This operation only returns roles that have been activated. A role becomes activated when an admin activates the role using the Activate directoryRole API. Not all built-in roles are initially activated.
When assigning a role using the Azure portal, the role activation step is implicitly done on the admin's behalf. To get the full list of roles that are available in Azure AD, use List directoryRoleTemplates.
For more information: https://learn.microsoft.com/en-us/graph/api/directoryrole-list?view=graph-rest-1.0&tabs=http#example

Graph API has Privileged Identity Management API. I'm not familiar with this API but you can retrieve the requests for role eligibilities for principals:
https://learn.microsoft.com/en-us/graph/api/rbacapplication-list-roleeligibilityschedulerequests?view=graph-rest-1.0&tabs=http
Documentation
Privileged Identity Management

Related

Microsoft Graph - Access Deneined when accessing to calendar events with specifiying user

I am working on creating application which uses Microsoft Graph API to access to calendar events for the users that belongs to an organization.
There is no issue getting event using below endpoint
https://graph.microsoft.com/v1.0/me/calendar/events
However, when accessing to below end point cause 403 error.
https://graph.microsoft.com/v1.0/users/xxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/calendar/events
403 - Forbidden
{"error":{"code":"ErrorAccessDenied","message":"Access is denied. Check credentials and try again."}}
So far I have below:
Application is registed to Aure with granting
Application.ReadWrite.All
Calendars.ReadWrite
offline_access
User.ReadWrite.All
Have logic to retrieve the access / refresh token.
When the access token is decoded, below scoes are availalbe
"scp": "Application.ReadWrite.All Calendars.ReadWrite User.ReadWrite.All profile openid email"
Others:
Below endpoints work
https://graph.microsoft.com/v1.0/users
https://graph.microsoft.com/v1.0/users/xxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
Below endpoints errors with access denied
https://graph.microsoft.com/v1.0/users/xxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/calendars
I also tried using User Principal Name instead of ID but it didn't make any difference.
Can someone please help why I am not able to access to the user calendar / events when specifying the user?
Error message showed Access is denied, we can understand that your account doesn't have enough permission to call that api(querying others' calendar events). Since the request calling only related with the access token, no matter whether you have an admin role or not. So let's assume whether you want other users to sign in your app and then they are able to query your calendar events.
According to your description, your token contained scp claim, so I'm sure you are using the delegate permission, which means you signed in and calling api on behalf yourself. And this may be the reason why the access is denied.
We can see the permissions in the screenshot above, I think the application permission type can solve your issue. Using permission type means the api calling is executed by your application itself, but not on behalf of some user. So the application can query any users' calendar events in your tenant.
Using application permission required you to assign application api permission like screenshot below.
Then if you are just testing via tools like postman, using request below to generate access token:
POST https://login.microsoftonline.com/{tenant}/oauth2/v2.0/token
Content-Type: application/x-www-form-urlencoded
client_id=535fb089-9ff3-47b6-9bfb-4f1264799865
&scope=https%3A%2F%2Fgraph.microsoft.com%2F.default
&client_secret=sampleCredentia1s
&grant_type=client_credentials
If are composing an asp.net core application and trying to call graph api via graph sdk, follow code snippet below:
using Microsoft.Graph;
using Azure.Identity;
var scopes = new[] { "https://graph.microsoft.com/.default" };
var tenantId = "tenant_name.onmicrosoft.com";
var clientId = "aad_app_id";
var clientSecret = "client_secret";
var clientSecretCredential = new ClientSecretCredential(
tenantId, clientId, clientSecret);
var graphClient = new GraphServiceClient(clientSecretCredential, scopes);
var events = await graphClient.Users["{user_id}"].Events
.Request()
.Header("Prefer","outlook.timezone=\"Pacific Standard Time\"")
.GetAsync();
Whenever you are trying to access another user calendar events, make sure you have Calendars.Read delegated permission , you can check what type of permission you have in azure portal -
https://learn.microsoft.com/en-us/graph/migrate-azure-ad-graph-configure-permissions?tabs=http%2Cupdatepermissions-azureadgraph-powershell

Error Access denied when trying to get mailfolders using Graph Api?

I am trying to rech the endpoint
https://graph.microsoft.com/v1.0/users/{emailaddress}/mailFolders('InBox') but am receiving
Error Access Denied response.
I have granted both Mail.Read.Shared and Mail.ReadWrite.Shared on delegated permission.
The scenario I have is that in Azure AD there are a number of users , Manager#acme.com and Tests#acme.com , so they exist under the same tennant /organization.
I have an app whereby I login as Manager#acme.com as the current user. I the create a connection to the App using client id , secret etc and receive an Auth toke n to use in my api calls.
but when i try to call
https://graph.microsoft.com/v1.0/users/Tests#acme.com/mailFolders('InBox') with that token I
get the following error:
{
"error": {
"code": "ErrorAccessDenied",
"message": "Access is denied. Check credentials and try again."
}
}
Do i ned to grant both Mail.Read.Shared and Mail.ReadWrite.Shared on Application level ?
Or do i need to create a shared folder in Outlook ?
I don't believe Mail.Read.Shared or Mail.ReadWrite.Shared exist as assignable application permissions.
The only permission your App Registration should need is Mail.Read, unless you're intending on the using Graph to delete / send emails etc.
You will likely also need an ApplicationAccessPolicy. You can either create one in the Exchange Online Admin Center, or through PowerShell. I recommend you create a mail enabled security group for all addresses which you need to access and grant restricted access to your app through that policy.
I prefer PowerShell, so in that case you would need the ExchangePowerShell module, and connect to Exchange Online. You'll need some Exchange admin role to be able to do this.
So, let's assume you've created a mail enabled security group called GraphAccessibleUsers#acme.com. You can set the property to hide this from the GAL so users can't see it.
You would then create a policy as follows:
New-ApplicationAccessPolicy -AccessRight RestrictAccess -AppId "<Your-App-Registration-Id" -PolicyScopeGroupId GraphAccessibleUsers#acme.com -Description "Allow App access to users in GraphAccessibleUsers#acme.com"
The -PolicyScopeId parameter will accept:
Name
Distinguished name (DN)
Display name
Email address
GUID
If you only have a few addresses, you may opt to create an individual ApplicationAccessPolicy for each email address.
Finally, I don't think your Graph API URI is correct.
If you want to access the Inbox of Tests#acme.com, then try this instead:
https://graph.microsoft.com/v1.0/users/Tests#acme.com/mailFolders/Inbox
Please refer to mailFolder Resource Type here.

microsoft graph rest api beta: application created by api in azure ad b2c is not valid

i'm trying to create ad application using beta api by following this document:
https://learn.microsoft.com/en-us/graph/api/application-post-applications?view=graph-rest-beta&tabs=http
the application can be successfully created in Azure AD B2C (not Azure Active Directory) as expected. the issue is when i'm trying to open this app from portal, the page just keeps loading while the app information never shows. i can see there's an error from browser dev tool:
The following request returns 404 error:
https://main.b2cadmin.ext.azure.com/api/ApplicationV2/GetApplication?tenantId=mytestb2ctenant.onmicrosoft.com&applicationId=560df329-47f5-497b-a1d3-08e9e8208062
I can verify the applicationId is indeed the appid of my newly created ad app. not sure why getting the notfound error.
Then I manually created another app in my b2c ad. I compared the returned schema from get-application rest api for these two apps. the only difference is the manually created one has a default user_impersonation api scope, while other one does not. maybe this causes the error.
here's my complete powershell script to created ad app:
$b2cDomain = "mytestb2ctenant.onmicrosoft.com"
$applications = "https://graph.microsoft.com/beta/applications"
$headers = #{
"Authorization" = $accessToken;
}
#app = "mytestapp"
$request = #{
displayName = $app
identifierUris = #("https://$b2cDomain/api")
signInAudience = "AzureADandPersonalMicrosoftAccount"
web = #{
redirectUris = #("https://any.valid.url")
implicitGrantSettings = #{
enableIdTokenIssuance = $false
enableAccessTokenIssuance = $true
}
}
isFallbackPublicClient= $false
}
$body = $request | ConvertTo-Json
Log "creating ad app: $app"
$appResponse = Invoke-RestMethod `
-Uri $applications `
-Method Post `
-Headers $headers `
-ContentType "application/json" `
-Body $body
did I miss anything for the request schema? how can i create a valid app from rest api just like i manually create it?
guess i found the root.
the application created from api did not have a service principle associated. need to create a sp for it. i could not find the rest api for creating sp from here. ended up using AzueAD powershell commands:
Connect-AzureAD -Credential $credential -TenantId $b2cTenantId
New-AzureADApplication -DisplayName "myapp"
$app = Get-AzureADApplication -SearchString "myapp"
New-AzureADServicePrincipal -AppId $app.AppId
everything seems working now.
btw, the Application in Azure AD B2C and in Azure Active Directory should be the same thing only showing different places. i got confused before.
Please remember not to use Microsoft Graph beta apis in production since they are subject to change.
For an application to successfully work in AAD B2C(get a token), it has following requirements
A service principal
Consent to openid and offline_access scope on
Microsoft Graph service principal in the tenant
The service principal apis are in Beta right now. The OAuth2Permissions api are in beta as well.
The algorithm is
Create an app using application api
Create a Service principal for it (lets call it clientSP).
Find service principal corresponding to Microsoft Graph app (AppId # 00000003-0000-0000-c000-000000000000) in tenant using service principal apis. This service principal is always created by Azure AD in the directory so you just need to search for it. Lets call is ResourceSP
Use OAUTH2Permissions api to create and grant consent to clientSP on ResourceSP for openid and offline_access scopes.
The sample here should help - https://github.com/valnav/Azure-AD-B2C-App-Graph.

Get Azure AD directory users in a Rails app

I have a Rails 6 application and I want to use Azure Active Directory as an authentication system (with open id connect, saml2 and ldap).
The authentication is done.
Now I am trying to display user information like names or email addresses. I also want to be able to export all users of a directory.
I have tried to set a configuration up like so:
In my Rails app, in the admin panel, an admin can configure Azure AD for my application
in the config, the admin copies and pastes the configuration link provided by Azure AD (a JSON response)
Then, copies and pastes the app client_id
Then, the tenant_id (directory id)
Here is a piece of code that I expected to work:
def update_oidc
identity_provider = IdentityProvider.find_by(provider_type: 'open_id_connect', id: params[:id])
client_id = params[:client_id].strip
metadata_url = params[:metadata_url].strip
tenant_id = params[:tenant_id].strip
metadata = HTTParty.get(metadata_url).parsed_response
identity_provider.update(config: {
metadata: metadata,
metadata_url: metadata_url,
client_id: client_id,
tenant_id: tenant_id,
})
if tenant_id
directory_access_url = "https://graph.windows.net/#{tenant_id}/users?api-version=1.6"
result = HTTParty.get(directory_access_url).parsed_response
identity_provider.directories.find_or_create_by(tenant_id: tenant_id).update(
business_phones: result["business_phones"],
display_name: result["display_name"],
given_name: result["given_name"],
job_title: result["job_title"],
email: result["user_principal_name"],
mobile_phone: result["mobile_phone"],
office_location: result["office_location"],
surname: result["surname"]
)
end
redirect_to identity_provider
end
As the tenant_id is the directory id, i thought that we might be able to access user info this way (and following the Microsoft Docs). The thing is, it doesn't work because even though I'm connected to my Azure AD directory in my app, when I run result = HTTParty.get(directory_access_url).parsed_response, i have an authentication error telling me the token has expired or that i need to be connected.
I don't want to use PowerShell or anything like this. I want to be able to access directories data through my app.
Can someone tell me what i'm doing wrong or come up with an idea ?
Thanks
Just according to your code, I think you want to get the collection of users via the Azure AD Graph REST API Get users using jnunemaker/httparty library.
However, it seems to be missing the required header Authorization with its value like Bearer eyJ0eX ... FWSXfwtQ as the section Authentication and authorization of the offical document Operations overview | Graph API concepts said. Meanwhile, you have done the authentication with OpenID Connect, but Azure AD Graph API requires the access token as Authorization value from OAuth2 as the content below said.
The Graph API performs authorization based on OAuth 2.0 permission scopes present in the token. For more information about the permission scopes that the Graph API exposes, see Graph API Permission Scopes.
In order for your app to authenticate with Azure AD and call the Graph API, you must add it to your tenant and configure it to require permissions (OAuth 2.0 permission scopes) for Windows Azure Active Directory. For information about adding and configuring an app, see Integrating Applications with Azure Active Directory.
Azure AD uses the OAuth 2.0 authentication protocol. You can learn more about OAuth 2.0 in Azure AD, including supported flows and access tokens in OAuth 2.0 in Azure AD.
So I'm afraid you have to get the access token manually via OAuth2 for Azure AD again for using Graph API, or just simply refer to the sample code samples/authorization_code_example/web_app.rb using the adal library of GitHub repo AzureAD/azure-activedirectory-library-for-ruby for Ruby.

Microsoft Graph to access and modify application object in Azure AD

I would like to know if it is possible to use Microsoft Graph instead of Azure AD Graph APIs to create and modify Application objects in AAD.
In particular I'm interested in updating permissions to the newly created app. Currently I'm using the following powershell script to add a permission to the app object
$url = "https://graph.windows.net/$tentant_id/applications/$($ad_app.ObjectID)?api-version=1.6"
$postData = "{`"requiredResourceAccess`":[{`"resourceAppId`":`"00000002-0000-0000-c000-000000000000`",`"resourceAccess`":[{`"id`":`"311a71cc-e848-46a1-bdf8-97ff7156d8e6`",`"type`":`"Scope`"}]}]}"
$result = Invoke-RestMethod -Uri $url -Method "PATCH" -Headers $authHeader -Body $postData
How do I achieve the same with "https://graph.microsoft.com" endpoint?
The beta endpoint has the application resource type with which you can create new applications, and modify them.

Resources