Skip to content

Instantly share code, notes, and snippets.

@christothes
Last active July 9, 2020 13:48
Show Gist options
  • Save christothes/6cb4b6e7eb74fb76da2aa99ea98fe1e4 to your computer and use it in GitHub Desktop.
Save christothes/6cb4b6e7eb74fb76da2aa99ea98fe1e4 to your computer and use it in GitHub Desktop.
RBAC Sample

RBAC Key concepts

RoleDefinition

A RoleDefinition is a collection of permissions. A role definition defines the operations that can be performed, such as read, write, and delete. It can also define the operations that are excluded from allowed operations.

RoleDefinitions can be listed and specified as part of a RoleAssignment.

RoleAssignment.

A RoleAssignment is the association of a RoleDefinition to a service principal. They can be created, listed, fetched individually, and deleted.

Expected Usage

Create the KeyVaultAccessControlClient

KeyVaultAccessControlClient client = new KeyVaultAccessControlClient(vaultUri: new Uri(keyVaultUrl), credential: new DefaultAzureCredential());

List the role definitions

List the role definitions available for assignment.

Pageable<RoleDefinition> allDefinitions = client.GetRoleDefinitions(RoleAssignmentScope.Global);

foreach (RoleDefinition roleDefinition in allDefinitions)
{
    Console.WriteLine(roleDefinition.Id);
    Console.WriteLine(roleDefinition.RoleName);
    Console.WriteLine(roleDefinition.Description);
}

Create, Get, and Delete a role assignment

Assign a role to a service principal. This will require a role definition id from the list retrieved in the above snippet and the principal object id retrieved in the Create/Get credentials

// Replace roleDefinitionId with a role definition Id from the definitions returned from the List the role definitions section above
string definitionIdToAssign = roleDefinitionId;

// Create a role assignment.
RoleAssignmentProperties properties = new RoleAssignmentProperties(definitionIdToAssign, servicePrincipalObjectId);
RoleAssignment createdAssignment = client.CreateRoleAssignment(RoleAssignmentScope.Global, properties);

Console.WriteLine(createdAssignment.Name);
Console.WriteLine(createdAssignment.Properties.PrincipalId);
Console.WriteLine(createdAssignment.Properties.RoleDefinitionId);

// Get the role assignment we created.
RoleAssignment fetchedAssignment = client.GetRoleAssignment(RoleAssignmentScope.Global, createdAssignment.Name);

Console.WriteLine(fetchedAssignment.Name);
Console.WriteLine(fetchedAssignment.Properties.PrincipalId);
Console.WriteLine(fetchedAssignment.Properties.RoleDefinitionId);

// Delete the role assignment.
RoleAssignment deletedAssignment = client.DeleteRoleAssignment(RoleAssignmentScope.Global, createdAssignment.Name);

Console.WriteLine(deletedAssignment.Name);
Console.WriteLine(deletedAssignment.Properties.PrincipalId);
Console.WriteLine(deletedAssignment.Properties.RoleDefinitionId);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment