I am trying to create a new Resource Group, a new Active Directory User and then assign the User to the Resource Group as a Contributor.
So far I have used the Microsoft.Azure.Management.ResourceManager to create the Resource Group successfully and the AD User with the Microsoft.Graph. I can see both in Azure and can access them both.
However, I can't find clearly how to assign the user to the resource group with C# in either the Resource Manager or Graph API.
I can see how to do it in everything else here > https://learn.microsoft.com/en-us/azure/role-based-access-control/role-assignments-portal
I have taken that as being the Graph API call graphClient.DeviceManagement.RoleAssignments
However, from the properties I can't clearly see where I put the Resource Group details.
This is my attempt below, but I get an error:
Request not applicable to target tenant
var roleAssignment = await graphClient.DeviceManagement.RoleAssignments.Request().AddAsync(new DeviceAndAppManagementRoleAssignment
{
DisplayName = "Test Role",
Members = new List<string>
{
createdUser.Id // GUID of new User
},
ResourceScopes = new List<string>
{
"/subscriptions/04cbb440-e619-4c8f-869f-8dc4d7dd6e42/resourceGroups/NewResourceGroup" // ID of Resource Group
},
RoleDefinition = new RoleDefinition
{
RolePermissions = new List<RolePermission> {
new RolePermission {
ResourceActions = new List<ResourceAction>
{
new ResourceAction {
AllowedResourceActions = new List<string> {"*"},
NotAllowedResourceActions = new List<string>
{
"Microsoft.Authorization/*/Delete",
"Microsoft.Authorization/*/Write",
"Microsoft.Authorization/elevateAccess/Action"
}
}
}
}
}
}
}).ConfigureAwait(false);
Can someone either tell me how I can easliy do this or where to look?
As far as I know, we should use Azure management REST API to to manage access to Azure resources.
The RBAC Graph API is for Intune requires an active Intune license for the tenant. It manages the role based access in Intune.
Related
I'm trying to use the Azure AD Graph API to create an API Scope for an Azure AD B2C application. This is the operation performed using the "Expose an API" blade in the portal.
I've tried adding the scope directly to the application like so:
var current = await graphClient.Applications[appId].Request().GetAsync();
var currentList = current.Api.Oauth2PermissionScopes ?? new List<PermissionScope>();
var newScope = new PermissionScope
{
AdminConsentDescription = scopeDescription,
AdminConsentDisplayName = scopeDescription,
IsEnabled = true,
Type = "Admin",
Value = scopeName
};
var updated = new Application {
Api = new ApiApplication {
Oauth2PermissionScopes = currentList.Append(newScope).ToList()
}
};
await graphClient.Applications[appId].Request().UpdateAsync(updated);
However, when I do that, I get an exception:
Microsoft.Graph.ServiceException
Code: ValueRequired
Message: Property api.oauth2PermissionScopes.id value is required but is empty or missing.
Does this mean that I need to create the scope separately then add it to the application? Looking over the Graph API docs, it isn't obvious how to do that and I haven't found any articles that discuss it, either.
How do you use Graph API to create API scopes?
if you want to use the Microsoft Graph API to create an API Scope for an Azure AD B2C application, we need to define PermissionScope object. The object should provide id(it is GUID).
For example
Register Application
Grant API permissions
Under Manage, select API permissions.
Under Configured permissions, select Add a permission.
Select the Microsoft APIs tab, then select Microsoft Graph.
Select Application permissions.
Select the checkbox of the permission Application.ReadWrite.All to grant to your application.
Select Add permissions. As directed, wait a few minutes before proceeding to the next step.
Select Grant admin consent for (your tenant name).
Create a client secret
code
static async Task Main(string[] args)
{
string clientId = "0159ec7d-f99f-***";
string clientSecret = "G_fM3QKa***essTRX23t1_o";
string tenantDomain = "{your tenat name}.onmicrosoft.com";
IConfidentialClientApplication confidentialClientApplication = ConfidentialClientApplicationBuilder
.Create(clientId)
.WithTenantId(tenantDomain)
.WithClientSecret(clientSecret)
.Build();
ClientCredentialProvider authProvider = new ClientCredentialProvider(confidentialClientApplication);
GraphServiceClient graphClient = new GraphServiceClient(authProvider);
var id = "fa89ac50-d5fd-47cb-9f3f-833f413a2ed4";
var app =await graphClient.Applications[id].Request().GetAsync();
var updated = new Application();
if (app.IdentifierUris.ToList().Count == 0) {
updated.IdentifierUris = new string[] { $"https://{tenantDomain}/{app.AppId}" };
}
var appscope = app.Api.Oauth2PermissionScopes.ToList();
var newScope = new PermissionScope
{
Id = Guid.NewGuid(),
AdminConsentDescription = "Allow the application to have read-only access to all Employee data",
AdminConsentDisplayName = "Read-only access to Employee records",
IsEnabled = true,
Type = "Admin",
Value = "Employees.Read.All"
};
appscope.Add(newScope);
updated.Api = new ApiApplication { Oauth2PermissionScopes =appscope };
await graphClient.Applications[id].Request().UpdateAsync(updated);
}
For more details, please refer to here.
In my Azure B2C directory I have created a custom attribute called EmployeeId. I am creating the users with the Microsoft Graph library. I followed the example from this GitHub Example.
My actual user creation code looks like this:
public async Task InsertEmployee(Employee employee)
{
IDictionary<string, object> extensionInstance = new Dictionary<string, object>();
extensionInstance.Add("EmployeeId", employee.EmployeeId.ToString());
var user = new B2cUserModel
{
DisplayName = $"{employee.EmployeeFirstName} {employee.EmployeeLastName}",
GivenName = employee.EmployeeFirstName,
Surname = employee.EmployeeLastName,
Password = employee.Password,
Identities = new List<ObjectIdentity> {
new ObjectIdentity {
SignInType = "emailAddress",
IssuerAssignedId = employee.EmployeeEmail
}
},
EmployeeId = employee.EmployeeId.ToString()
AdditionalData = extensionInstance
};
user.SetB2CProfile(_domain);
await _client.Users.Request().AddAsync(user);
}
}
But whenever I retrieve the user details either through code or through a user_flow EmployeeId is always null. Can anyone spot what I'm doing wrong?
The custom attribute in Azure B2C is stored in Graph as such a format: extension_{client id of WebApp-GraphAPI-DirectoryExtensions}_{custom attribute}. See reference here.
You can find the client id of WebApp-GraphAPI-DirectoryExtensions Azure AD app in Azure Portal -> App registrations.
So in this case, you should use:
extensionInstance.Add("extension_{client id of WebApp-GraphAPI-DirectoryExtensions}_EmployeeId", employee.EmployeeId.ToString());
I'm trying to follow the Resource group authenticate service principal to be able to access some resource manager stuff. But when trying to do anything, I get the following error:
SubscriptionNotFound: The subscription 'resourceGroups' could not be found.
Using the C# code in the article to get an access token, and then calling the follow methods:
var dnsClient = new DnsManagementClient(new Microsoft.Azure.TokenCloudCredentials(result.AccessToken));
var zone = dnsClient.Zones.CreateOrUpdate("someresourcegroup", "mydomain.com", new Microsoft.Azure.Management.Dns.Models.ZoneCreateOrUpdateParameters {
IfNoneMatch = "*",
Zone = new Microsoft.Azure.Management.Dns.Models.Zone {
Name = "mydomain.com",
Location = "northeurope"
}
});
Any idea what I'm doing wrong? I've created a service principal as a Contributor, so permissions shouldn't be a problem?
The error message says The subscription 'resourceGroups' could not be found, please try specify your subscriptionid when creating the TokenCloudCredentials object.
var dnsClient = new DnsManagementClient(new Microsoft.Azure.TokenCloudCredentials("your_subscriptionid", result.AccessToken));
Tested from my side and it works.
I am looking to create a role based authorization mvc application using Azure AD:
Create a .NET MVC web app in Azure App Service with Azure Active Directory authentication
Azure Role-based Access Control
From the Azure Portal, I am able :
To create user and groups.
To assign user to group.
To create applications roles.
To create application roles (by modifying the manifest)
To assign an application role to a user.
I've just had a free Azure Active Directory edition and I've readed that we can use the Microsoft Azure Active Directory to perform these actions :
To assign multiple application roles to users.
To assign multiple application roles to groups.
Microsoft provides good samples to query the AAD and I've started with it but I can't figured out how to assign an application to a group.
Here is my pseudo code to get the group:
ActiveDirectoryClient client = AuthenticationHelper.GetActiveDirectoryClient();
var app = (await client.Applications.GetByObjectId("applicationObjectId").ExecuteAsync());
var servicePrincipal = await client.ServicePrincipals.GetByObjectId("servicePrincipalObjectId").ExecuteAsync();
var appRole = app.AppRoles.First(r => r.DisplayName == "my role");
var mygroup = (await client.Groups.ExecuteAsync()).CurrentPage.FirstOrDefault();
What I would like to do is something like that :
mygroup .AppRoleAssignments.Add(new AppRoleAssignment()
{
ResourceId = Guid.Parse(servicePrincipal.ObjectId),
Id = appRole.Id,
PrincipalType = "Group",
PrincipalId = Guid.Parse(mygroup .ObjectId),
});
await group.UpdateAsync();
But the type of the AppRoleAssignments is IPagedCollection<IAppRoleAssignment> and there is no Add method.
Does anyone knows what I need to chage in my code ?
In fact it was simple... I had to cast the IGroup as a Group :
ActiveDirectoryClient client = AuthenticationHelper.GetActiveDirectoryClient();
var app = (await client.Applications.GetByObjectId("applicationObjectId").ExecuteAsync());
var servicePrincipal = await client.ServicePrincipals.GetByObjectId("servicePrincipalObjectId").ExecuteAsync();
var appRole = app.AppRoles.First(r => r.DisplayName == "my role");
var mygroup = (Group)(await client.Groups.ExecuteAsync()).CurrentPage.FirstOrDefault();
And it works fine ^^ :
mygroup .AppRoleAssignments.Add(new AppRoleAssignment()
{
ResourceId = Guid.Parse(servicePrincipal.ObjectId),
Id = appRole.Id,
PrincipalType = "Group",
PrincipalId = Guid.Parse(mygroup .ObjectId),
});
await group.UpdateAsync();
How to connect couchDB with ASP.NET C# application? If any one can you give a sample application.
I had the same need and after evaluating the options available, to meet the requirements of my application, I created any components that helped me a lot and maybe they can help you and also others. I make it clear that I have no intention of promoting myself here, just sharing something that may be useful.
The detailed explanation of how to configure and use it is on Github.
Link: Nuget Package |
Github
Example of use for retrieving documents with mango-querie:
IList<User> users;
var sts = new List<String> { "ACTIVE", "LOCKED" };
using (UserRepository db = new UserRepository())
{
var query = db.FindOf("list-status", new { id = "OwnerIdloop.user.7", statuses = sts });
users = db.List<User>(query);
}
Array.ForEach(users.ToArray(), Console.WriteLine);
Example of adding documents:
User user = createUser("email#email.com");
using (UserRepository db = new UserRepository())
{
var result = db.Insert<User>(user); // add document and return instance changed with operation revision id
Console.WriteLine(result.Revision);
}
Example of changing documents:
using (UserRepository db = new UserRepository())
{
// Load document data by ID
var user = db.Get<User>("email#email.com");
user.Name = user.Name + "::CHANGED";
var result = db.Update<User>(user); // update document and return instance changed with operation revision id
Console.WriteLine(result.Revision);
}
Example of deleting documents:
using (UserRepository db = new UserRepository())
{
// Load document data by ID
var user = db.Get<User>("email#email.com");
var result = db.Delete<User>(user); // delete document from database. Return true case sucess or false case not deleted
Console.WriteLine($"Sucesso: {result}");
}
After installing the NuGet, just create an instance of MyCouch.Client and pass it the URL of your database.
using (var client = new MyCouchClient("http://127.0.0.1:5984/test"))
{
//Consume here
}
The format is: {scheme}://[{username}:{password}]/{authority}/{localpath}. From v0.11.0, there's a specific MyCouchUriBuilder that you can use for building the Uri. It will automatically e.g. apply Uri.EscapeDataString to username and password when calling SetBasicCredentials.
var uriBuilder = new MyCouchUriBuilder("http://localhost:5984/")
.SetDbName(TestConstants.TestDbName)
.SetBasicCredentials("foob#r", "p#ssword");
return new MyCouchClient(uriBuilder.Build());
For more details Click Here