Remove a user or group assignment to an enterprise app using Microsoft Graph - azure-active-directory

I would like to remove a user or group assignment to an enterprise app using Azure AD Graph or Microsoft Graph in C#.
Thanks,
Kevin

The answer provided by juunas is right, I just make some additions.
As you want to do this operation by c# code, so you can refer to my steps below:
1. Install two SDKs in your project.
Install-Package Microsoft.Graph.Auth -IncludePrerelease
Install-Package Microsoft.Graph.Beta -Version 0.14.0-preview
I referred to the document about install SDKs, but I can't find AppRoleAssignments in GraphServiceClient class. So please install SDKs with the commands above.
2. Please refer to the code below:
using Microsoft.Graph;
using Microsoft.Graph.Auth;
using Microsoft.Identity.Client;
using System;
using System.Security;
namespace ConsoleApp13
{
class Program
{
static async System.Threading.Tasks.Task Main(string[] args)
{
Console.WriteLine("Hello World!");
IPublicClientApplication publicClientApplication = PublicClientApplicationBuilder
.Create("your client id")
.WithTenantId("your tenantid")
.Build();
UsernamePasswordProvider authProvider = new UsernamePasswordProvider(publicClientApplication, new string[] { "https://graph.microsoft.com/.default" });
GraphServiceClient graphClient = new GraphServiceClient(authProvider);
var securePassword = new SecureString();
string password = "your password";
foreach (char c in password)
securePassword.AppendChar(c);
await graphClient.Users["user object id"].AppRoleAssignments["role assignment id"].Request().WithUsernamePassword("email account", securePassword).DeleteAsync();
Console.WriteLine("----complete---");
}
}
}
The role assignment id in AppRoleAssignments["role assignment id"] above comes from the list query graph api: GET https://graph.microsoft.com/beta/servicePrincipals/{id}/appRoleAssignedTo/{id}
3. Before running the c# code, we need to enable we have assign the delegated permission Directory.AccessAsUser.All to the app and enable the button shown as below screenshot.
4. After that, we can running the code and remove the user or group successfully.
5. By the way:
(1) The code I provided is for remove users assignment. If you want to remove group assignment, just modify the code as:
await graphClient.Groups["group object id"].AppRoleAssignments["role assignment id"].Request().WithUsernamePassword("email account", securePassword).DeleteAsync();
(2) You need to pay attention to the beta version of api as juunas mentioned.
Hope it helps~

To do that, you'd need to call this endpoint in MS Graph API: https://learn.microsoft.com/en-us/graph/api/approleassignment-delete?view=graph-rest-beta&tabs=http.
Though the docs seem to be missing it, you should be able to list the assignments for a user etc. by doing a GET without an assignment id.
I don't think you can guess the assignment ids, so you'll need to read them first from there.
And though it says you need delegated permissions to call the endpoint, that isn't completely true.
You can give an app the access as user permission and then login with a user and act on their behalf.
But you can also have an app do these without a user.
You can assign an administrator role to the service principal running a script, and that will allow it to do this as well.
You can do this through the Roles and administrators tab in the AAD management UI.
The only tough situation here is that this ability is only in the beta version of MS Graph API.
But Azure AD Graph API is not recommended for use.
So, you have two options right now:
Use the beta version of MS Graph API for this, and upgrade as soon as the API reaches a stable version
beta is a bit volatile, so there some risks in using it in production
Use Azure AD Graph API and upgrade to MS Graph API once it reaches a stable version
this upgrade would probably be mandatory

Related

How can I allow users of my connector to set a different username and password each time they create a new source?

I have build and published the Data Studio connector for TradeTracker. The connector works great, but when users try to add a different account by trying to add a new datasource they can't re-enter their API Clientid and passphrase. How do I clear the 'old' credentials?
I have found there's an function to reset the auth: https://developers.google.com/datastudio/connector/auth#resetauth.
function resetAuth() {
var userProperties = PropertiesService.getUserProperties();
userProperties.deleteProperty('dscc.username');
userProperties.deleteProperty('dscc.password');
}
When should I call this function?
You can find the data studio connector here: https://datastudio.google.com/u/0/datasources/create
Search for 'tradetracker'.
Multiple auth profiles are not currently supported by Data Studio. If you want to authenticate to a data source with different credentials, you need to remove the connector (which will call resetAuth), then add it again and use your new credentials.
If this feature would be useful to you, please file a bug, or vote on an existing one. We look at this component in part when trying to prioritize new features for Data Studio.

How do I get the "Assigned Role" of a User in Azure Active Directory?

I am using Azure AD with a registered Application and I am using the Microsoft Graph API to query the AD.
The following code below tells which groups the User is Assigned to
var memberof = await graphClient.Users[xxx].MemberOf.Request().GetAsync();
I am using standard AD package and it seems that groups are somewhat restricted and I need to buy the "Premium AD Package" to use them fully.
So I don't want to use the group information. I am interested in the roles that I assign my users that I have put into my application manifest.
e.g
"appRoles": [
{
"allowedMemberTypes": [
"User"
],
"displayName": "Case Manager",
"id": "{A_Guid}",
"isEnabled": true,
"description": "Case Manager's can create and assign Cases to other users",
"value": "CaseManager"
},
So, how can I use the Graph Api to tell me if a user has a particular role ?
1. Microsoft Graph API
The ability to read all application specific roles assigned to a user (i.e. AppRoleAssignments) is only available as part of Microsoft Graph API beta endpoint currently AFAIK. This is not available as part of v1.0. You can read about versions here
As evident from name "beta", it's not expected to be a stable version that can be relied upon for production applications. Read more specific points in this SO Post by Marc LaFleur
Exact API (Microsoft Docs Reference):
GET https://graph.microsoft.com/beta/users/{id | userPrincipalName}/appRoleAssignments
I tried using GraphServiceClient (.NET SDK for Microsoft Graph) but wasn't able to find anything related to AppRoleAssignments. (probably because SDK uses metadata from stable 1.0 version and not the beta version)
In any case, if you can still test this, use Microsoft Graph Explorer or directly call the endpoint from C# code
string graphRequest = $"https://graph.microsoft.com/beta/users/{my user GUID}/appRoleAssignments";
HttpClient client = new HttpClient();
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, graphRequest);
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", authResult.AccessToken);
HttpResponseMessage response = await client.SendAsync(request);
2. Windows Azure AD Graph API
Even though it's recommended to use Microsoft Graph API whenever possible, there are still some cases where Microsoft Graph hasn't caught up yet so you are forced to use Azure AD Graph API. Application management related cases are some of those.
So you could use this Azure AD Graph API. I quickly tested this from Azure AD Graph Explorer and it works fine.
https://graph.windows.net/{yourtenantid}/users/{id}/appRoleAssignments?api-version=1.6
Just like Microsoft Graph Library for .NET you can use Azure AD Graph Client Library for .NET and your code would look something like this..
aadgraphClient.Users["<user guid>"].AppRoleAssignments;
On a side note, since you've asked the question specifically for Microsoft Graph API, I've answered it accordingly.
At least for the currently signed in user for an application, you can always find the Application Roles assigned to them from the Role claims available as part of the access token from Azure Active Directory.
This although only helps with roles for current user and not in management sort of scenarios if you're trying to go across all users for an application. Here's a sample that reads role claims and does authorization based on App Roles for currently signed in user.
Authorization in a web app using Azure AD application roles & role claims
I just found a way to get roles of an user at an application level.
You can create application level roles by updating the manifest's appRoles array.
[azure/app registrations/<your-app>/manifest)]
I used Microsoft.Graph.Beta, to get access to service principals api.
var userRoles = await _client.Me.AppRoleAssignments.Request().GetAsync();
The above query would fetch all the application roles for the user.
var appRoleAssignments = await _Client.ServicePrincipals[<<application_objectId>>].Request().GetAsync();
The above query would fetch all the roles of an application assigned at manifest level.
And application object Id could be found at [azure/app registrations/<your-app>)] -> Object ID
And execute the below to get list of user roles
var roles = new List<string>();
if (appRoleAssignments != null && appRoleAssignments.AppRoles.Any())
{
var userRolesOfCurrentResource = userRoles.First(role => role.ResourceId == Guid.Parse(<<application object id>>));
if(userRolesOfCurrentResource!=null)
{
var role = appRoleAssignments.AppRoles.First(role => role.Id == userRolesOfCurrentResource.AppRoleId);
if (role!=null)
{
roles.Add(role.Value);
}
}
}

Identityserver and SQL server Database

we are looking for brand new implementation for Identityserver4,
I wnet thru the documentation and install the Project on VS2017 and DB in sqlserver.
Database is created with the default migration script provided for bot ConfigurationData as well as Operational DAta.
I am very much confused , where the user will be how the clients will be add etc?
Also in the startup the default ASPNEtIdentity is add, but in database there is no ApplicationUser table, so where the userdata will be?
My requirement is simple - User will be aple to login to application by his credentials(or may be by 3rd party application) and will use the application or
API will directly use Identity server to with clientcredential scope,
Here please do let me know:
Should I introduce AspNetIdentity or Not, and Why?
Where is the user table and Password of the user in the database generated by the migration.
How we can add User clients and resources to the Created Database
Do I need to add Login/Logout page ?
In API APIResource is used to defined the Resources "api1" and same is used by the client code to get the access but this "api1" is not used anywhere with the definition/signature of the Method, so ow will it be correlated?
First off, IdentityServer4 on it's own does not handle users or authentication thereof - you either need to use ASP.Net Identity and the integration library that hooks it up to IdentityServer4 or build all of that stuff yourself.
So to sum up:
Yes you'll need to use that or roll your own user store and authentication logic
Either provided by ASP.Net Identity or built yourself
https://www.identityserver.com/documentation/admin-ui/ may fit your needs or you could build your own tooling and/or scripts to do so
Yes although the quickstart samples provide good basic starting points
The bearer token middleware by default will validate the audience (ApiResource.Name) but I prefer to enforce scope at a more granular controller or action level using a filter (e.g. [ScopeAuthorize("my.api")] public MyResult ApiAction() { ... }). This filter will check that the specified scope is defined in the set of claims in the ClaimsPrincipal).

Unable to get user company information on microsoft graph API

I'm having a problem with Microsoft Graph API... Currently I have a web application that has an openid integration with Microsoft/Azure using the common v2 endpoint.
We are trying to get the signed in user company name and job information. The official docs say that we need to make a request to the MS Graph API.
We are testing it on Microft Graph Explorer but it doesn't seem to work.
We've selected the 'User.Read' as a permission in our app, then tried these endpoints:
https://graph.microsoft.com/v1.0/me/
https://graph.microsoft.com/v1.0/me?$select=companyName,jobTitle
https://graph.microsoft.com/v1.0/users/?$select=companyName,jobTitle
In MS offical doc (https://developer.microsoft.com/en-us/graph/docs/concepts/permissions_reference) on User/Remarks sections, it clearly says that
"On reads, only a limited number of properties are returned by default. To read properties that are not in the default set, use $select"
Is this doc outdated?
I've tried to reach MS support for developers, but they answered saying that I should ask this on Stack Overflow...
So probably there are no official support for developers?
Is it really possible to get the company name and job title from a MS account?
Thanks in advance!
edit. Update question with MS graph explorer screenshots
edit.2. Update screenshot with proper encoding.
Also, it's a MS account not an Azure account, since our web app accepts both of them on the common v2 endpoint.
Update
My goal was trying to get the Work Info section from a MSA account.
The documentation is correct, by default we only return a subset of user properties:
id
userPrincipalName
displayName
givenName
surname
jobTitle
mail
mobilePhone
businessPhones
officeLocation
preferredLanguage
If you want a different set of properties, you can request them using the $select query parameter. The queries you provided in your question should work fine. For example, when I execute https://graph.microsoft.com/v1.0/me?$select=companyName in Graph Explorer (after logging in with my credentials) I get the following:
{
"#odata.context": "https://graph.microsoft.com/v1.0/$metadata#users(companyName)/$entity",
"companyName": "MICROSOFT"
}
Update Regarding MSA
When using Microsoft Graph against a Microsoft Account (MSA) there are several differences in what properties get surfaced. As an MSA is by definition a personal/individual account, organizational properties such as Job Title and Office Location are simply not applicable.

Native App ADAL 3 w/ Microsoft Graph resource keep getting same scopes

I have a registered a native app (WPF) with AAD and set it up to have permissions to Microsoft Graph. I had a small set of delegated permissions to start. Everything worked great - ie, reading user's calendar.
I have added some additional permissions (SendMail specifically). When I want to use the Graph SDK to send email, I get an access error. When I check the access token returned by ADAL, it only contains the scopes "scp": "Calendars.Read offline_access Tasks.Read User.Read".
Pretty simple ADAL call...
_authClient = HermesAuthenticationClient.CreateAuthenticationClient(clientId, _redirectUri, authority);
var result = await _authClient.AcquireTokensAsync(resource, new PlatformParameters(PromptBehavior.Always));
Any pointers would be much appreciated.
There is a known issue involving changing scopes of an existing application. Because you have already authorized that application using the previous scopes, it is unaware of the additional scopes that have been requested. In other words, the old scopes you authorized are cached and the new scopes aren't recognized.
You'll need to manually revoke permissions for the application under "My Apps".
Alternatively you can generate new id's for the app which will also trigger the "request permission" workflow.

Resources