Azure AD Add AppRoleAssignment - azure

I am using Azure AD for the authentication service on an MVC application. I am managing the user accounts successfully using the Graph API. I am trying to add an AppRoleAssignment to the user.
string tenantID = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value;
string userObjectID = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;
Uri servicePointUri = new Uri(graphResourceID);
Uri serviceRoot = new Uri(servicePointUri, tenantID);
ActiveDirectoryClient activeDirectoryClient = new ActiveDirectoryClient(serviceRoot, async () => await GetTokenForApplication());
IUser user = new User();
user.JobTitle = "Tester";
user.DisplayName = "Test Tester";
user.Surname = "Tester";
user.GivenName = "Test";
user.UserPrincipalName = "ttester#test.com";
user.AccountEnabled = true;
user.MailNickname = "ttester";
user.PasswordProfile = new PasswordProfile
{
Password = "XXXXX",
ForceChangePasswordNextLogin = true
};
await activeDirectoryClient.Users.AddUserAsync(user);
var appRoleAssignment = new AppRoleAssignment
{
Id = Guid.Parse("XXXXX"),
ResourceId = Guid.Parse("XXXXX"),
PrincipalType = "User",
PrincipalId = Guid.Parse(user.ObjectId)
};
user.AppRoleAssignments.Add(appRoleAssignment);
await user.UpdateAsync();
The AppRoleAssignment is never made. I am not certain if it is the constructor variables.
The id I am placing the ID of the role, being created in the application manifest. The ResourceId I am placing the ObjectId of the application. The application is created under the AAD Directory.
The code actually completes without error, however inspecting the user it shows not AppRoleAssignments.
In the end I am trying to implement RBAC using application roles.
Any help is greatly appreciated.

To assign application role to a user, you need to cast the User object to IUserFetcher:
await ((IUserFetcher)user)
.AppRoleAssignments.AddAppRoleAssignmentAsync(appRoleAssignment);
I also had to set the ResourceId to the ServicePrincipal.ObjectId
var servicePrincipal = (await
activeDirectoryClient.ServicePrincipals.Where(
s => s.DisplayName == "MyApplicationName").ExecuteAsync()).CurrentPage
.First();
var appRoleAssignment = new AppRoleAssignment
{
Id = Guid.Parse("XXXXX"),
// Service principal id go here
ResourceId = Guid.Parse(servicePrincipal.ObjectId),
PrincipalType = "User",
PrincipalId = Guid.Parse(user.ObjectId)
};

Related

Programmatically authenticate AKS with Azure AD and Managed Identity

I'm new to AKS and the Azure Identity platform. I have an AKS cluster that is using the Azure AD integration. From an Azure VM that has a user assigned managed identity, I'm trying to run a C# console app to authenticate against Azure AD, get the kubeconfig contents and then work with the kubernetes client to perform some list operations. When the code below is run I get an Unauthorized error when attempting to perform the List operation. I've made sure that in the cluster access roles, the user assigned managed identity has the Owner role.
The code does the following:
Creates an instance of DefaultAzureCredential with the user managed identity ID
Converts the token from DefaultAzureCredential to an instance of Microsoft.Azure.Management.ResourceManager.Fluent.Authentication.AzureCredentials and authenticates
Gets the contents of the kubeconfig for the authenticated user
Gets the access token from http://169.254.169.254/metadata/identity/oauth2/token
Sets the access token on the kubeconfig and creates a new instance of the Kubernetes client
Attempt to list the namespaces in the cluster
I've pulled information from this POST as well from this POST.
I'm not sure if the scopes of TokenRequestContext is correct and if the resource parameter of the oauth token request is correct.
string userAssignedClientId = "0f2a4a25-e37f-4aba-942a-5c58f39eb136";
var credential = new DefaultAzureCredential(new DefaultAzureCredentialOptions { ManagedIdentityClientId = userAssignedClientId });
var defaultToken = credential.GetToken(new TokenRequestContext(new[] { "https://management.azure.com/.default" })).Token;
var defaultTokenCredentials = new Microsoft.Rest.TokenCredentials(defaultToken);
var azureCredentials = new Microsoft.Azure.Management.ResourceManager.Fluent.Authentication.AzureCredentials(defaultTokenCredentials, defaultTokenCredentials, null, AzureEnvironment.AzureGlobalCloud);
var azure = Microsoft.Azure.Management.Fluent.Azure.Authenticate(azureCredentials).WithSubscription("XXX");
var kubeConfigBytes = azure.KubernetesClusters.GetUserKubeConfigContents(
"XXX",
"XXX"
);
var kubeConfigRaw = KubernetesClientConfiguration.LoadKubeConfig(new MemoryStream(kubeConfigBytes));
var authProvider = kubeConfigRaw.Users.Single().UserCredentials.AuthProvider;
if (!authProvider.Name.Equals("azure", StringComparison.OrdinalIgnoreCase))
throw new Exception("Invalid k8s auth provider!");
var httpClient = new HttpClient();
var token = string.Empty;
using (var requestMessage =
new HttpRequestMessage(HttpMethod.Get, $"http://169.254.169.254/metadata/identity/oauth2/token?api-version=2018-02-01&resource={Uri.EscapeUriString("6dae42f8-4368-4678-94ff-3960e28e3630/.default")}&client_id={userAssignedClientId}"))
{
requestMessage.Headers.Add("Metadata", "true");
var response = await httpClient.SendAsync(requestMessage);
token = await response.Content.ReadAsStringAsync();
Console.WriteLine(token);
}
var tokenNode = JsonNode.Parse(token);
authProvider.Config["access-token"] = tokenNode["access_token"].GetValue<string>();
authProvider.Config["expires-on"] = DateTimeOffset.UtcNow.AddSeconds(double.Parse(tokenNode["expires_in"].GetValue<string>())).ToUnixTimeSeconds().ToString();
var kubeConfig = KubernetesClientConfiguration.BuildConfigFromConfigObject(kubeConfigRaw);
var kubernetes = new Kubernetes(kubeConfig);
var namespaces = kubernetes.CoreV1.ListNamespace();
foreach (var ns in namespaces.Items)
{
Console.WriteLine(ns.Metadata.Name);
var list = kubernetes.CoreV1.ListNamespacedPod(ns.Metadata.Name);
foreach (var item in list.Items)
{
Console.WriteLine(item.Metadata.Name);
}
}
Any help is appreciated!
Try using the resource in the token request without /.default.
So it should be:
resource=6dae42f8-4368-4678-94ff-3960e28e3630

Unable to Create Pool using Azure Batch Management Library with ServiceClientCrenetials generated via AzureCredentialsFactory

I am using this documentation to assign a managed identity to my Batch Pool. For simplicity I do not include that assignment in the examples below as the issue is not tied to that but rather to accessing the management library with my credentials and just being able to generate a new pool on my existing batch account.
I'm using a Service Principal to generate ServiceClientCredntials via AzureCredentialsFactory to use with the Microsoft.Azure.Management.Batch library.
The Service Principal has Azure Service Management permissions enabled with user_impersonation set as Delegated. It is also assigned as a Contributor role on the subscription.
I am able to create the credentials with the following code
using Microsoft.Azure.Management.Batch.Models;
using Microsoft.Azure.Management.ResourceManager.Fluent;
using Microsoft.Azure.Management.ResourceManager.Fluent.Authentication;
string subscriptionId = "<subscriptionId>";
string tenantId = "<tenantId>";
string servicePrincipalId = "<servicePrincipalId>";
string servicePrincipalKey = "<servicePrincipalKey>";
var creds = new AzureCredentialsFactory().FromServicePrincipal(servicePrincipalId, servicePrincipalKey, tenantId, AzureEnvironment.AzureGlobalCloud).WithDefaultSubscription(subscriptionId);
var managementClient = new Microsoft.Azure.Management.Batch.BatchManagementClient(creds);
However when I attempt to use the credentials to create a pool in my Azure Batch account I get the following exception:
Microsoft.Rest.ValidationException: ''this.Client.SubscriptionId' cannot be null.'
I'm using .WithDefaultSubscription(subscriptionId) and have verified that the default subscription is set on the credentials prior to creating the BatchManagementClient.
Here is the code I am using to create the pool
var poolId = "test-pool";
var batchResourceGroupName = "<resourceGroupName>";
var batchAccountName = "<batchAccountName>";
var poolParameters = new Pool(name: poolId)
{
VmSize = "STANDARD_D8S_V3",
DeploymentConfiguration = new DeploymentConfiguration
{
VirtualMachineConfiguration = new VirtualMachineConfiguration(
new ImageReference(
"Canonical",
"UbuntuServer",
"18.04-LTS",
"latest"),
"batch.node.ubuntu 18.04")
}
};
var pool = await managementClient.Pool.CreateWithHttpMessagesAsync(
poolName: poolId,
resourceGroupName: batchResourceGroupName,
accountName: batchAccountName,
parameters: poolParameters,
cancellationToken: default(CancellationToken)).ConfigureAwait(false);
I am able to list my subscriptions with the credentials using
IAzure azure = Azure.Authenticate(creds).WithDefaultSubscription();
var subscriptions = azure.Subscriptions.List().ToList();
And I see the subscriptions that this service principal has access to in that list. So I know the credentials are good.
The exception occurs on this line
var pool = await managementClient.Pool.CreateWithHttpMessagesAsync(...
And here is the FULL CODE
using Microsoft.Azure.Management.Batch.Models;
using Microsoft.Azure.Management.ResourceManager.Fluent;
using Microsoft.Azure.Management.ResourceManager.Fluent.Authentication;
string subscriptionId = "<subscriptionId>";
string tenantId = "<tenantId>";
string servicePrincipalId = "<servicePrincipalId>";
string servicePrincipalKey = "<servicePrincipalKey>";
var poolId = "test-pool";
var batchResourceGroupName = "<resourceGroupName>";
var batchAccountName = "<batchAccountName>";
var poolParameters = new Pool(name: poolId)
{
VmSize = "STANDARD_D8S_V3",
DeploymentConfiguration = new DeploymentConfiguration
{
VirtualMachineConfiguration = new VirtualMachineConfiguration(
new ImageReference(
"Canonical",
"UbuntuServer",
"18.04-LTS",
"latest"),
"batch.node.ubuntu 18.04")
}
};
var creds = new AzureCredentialsFactory().FromServicePrincipal(servicePrincipalId, servicePrincipalKey, tenantId, AzureEnvironment.AzureGlobalCloud).WithDefaultSubscription(subscriptionId);
var managementClient = new Microsoft.Azure.Management.Batch.BatchManagementClient(creds);
var pool = await managementClient.Pool.CreateWithHttpMessagesAsync(
poolName: poolId,
resourceGroupName: batchResourceGroupName,
accountName: batchAccountName,
parameters: poolParameters,
cancellationToken: default(CancellationToken)).ConfigureAwait(false);
---- UPDATE ----
I added the following line before calling Pool.CreateWithHttpMessageAsync()
managementClient.SubscriptionId = subscriptionId;
And am no longer getting an error regarding null subscriptionId and can now use the management client as expected.

How do I create a user in code, add it Azure AD B2C, then log in as that user using Azure AD B2C OAuth (MSAL)

Having read the documentation here I thought I should be able to add a user to active directory B2C and then be able to log in as that user. The error message is: "We can't seem to find your account"
[TestMethod]
public async Task CreateUserTest()
{
string mailNickname = Guid.NewGuid().ToString();
string upn = mailNickname + "#mydomain.onmicrosoft.com";
string email = "zzz#gmail.com";
User record = new User { Email = email, DisplayName = "Bob Smith", MailNickname = mailNickname, UserPrincipalName = upn };
record.Identities = new List<ObjectIdentity>();
record.PasswordProfile = new PasswordProfile();
record.Identities.Append(new ObjectIdentity { Issuer = "mydomain.onmicrosoft.com", IssuerAssignedId = email, ODataType = "microsoft.graph.objectidentity", SignInType = "emailAddress" });
record.Identities.Append(new ObjectIdentity { Issuer = "mydomain.onmicrosoft.com", IssuerAssignedId = upn, ODataType = "microsoft.graph.objectidentity", SignInType = "userPrincipalName" });
record.PasswordProfile.Password = "Abcdefgh123!!";
record.AccountEnabled = true;
record.PasswordProfile.ForceChangePasswordNextSignIn = false;
User user = await graphService.CreateUser(record);
Assert.IsNotNull(user);
}
public async Task<User> CreateUser(User user)
{
var result = await client.Users.Request().AddAsync(user);
return user;
}
This login code works if the user logs in using an existing account or creates a new one using the Sign up now link:
export const SignIn = async (appState: AppState): Promise<string> => {
var msg: string = '';
try {
const response = await MSAL.login('loginPopup');
Edit: Add screen cap showing user type and source:
I tried to create a consumer user with code like yours:
And tested with this account in user flow, it returned the token well:
Please check the accounts that you created in your code, the User type always need to be Member and have the Source Azure Active Directory.

MS graph API cannot grant Application roles

I am not able to grant the Application role using graph API. Below is the code
Code
IConfidentialClientApplication app = ConfidentialClientFactory.SpnAuthenticate(_configuration["ClientId"],
_configuration["ClientSecret"],
_configuration["TenantId"]);
ClientCredentialProvider authProvider = new ClientCredentialProvider(confidentialClientApplication: app);
Beta.GraphServiceClient graphClient = new Beta.GraphServiceClient(authProvider);
var appRoleAssignment = new Beta.AppRoleAssignment
{
AppRoleId = model.appRoleId,
ResourceId = model.resourceId,
ResourceDisplayName = "resourceDisplayName-value"
};
var respone = await graphClient.ServicePrincipals[model.servicePrincipalId].AppRoleAssignments
.Request()
.AddAsync(appRoleAssignment);
Error
Status Code: BadRequest
Microsoft.Graph.ServiceException: Code: Request_BadRequest
Message: Not a valid reference update.
Inner error:
AdditionalData:
request-id: 9e94e7e1-b4bf-415e-8aee-7d6d199dbe1b
date: 2020-04-26T06:43:59
ClientRequestId: 9e94e7e1-b4bf-415e-8aee-7d6d199dbe1b
App role assignment function properpties
appRoleId
creationTimestamp
PrincipalDisplayName
principalId
principalDisplayName
resourceDisplayName
ResourceId
Can anyone help me to figure out the correct code?
I found the issue. Thanks #juunas
Updated Code:
IConfidentialClientApplication app = ConfidentialClientFactory.SpnAuthenticate(_configuration["ClientId"],_configuration["ClientSecret"],_configuration["TenantId"]);
ClientCredentialProvider authProvider = new ClientCredentialProvider(confidentialClientApplication: app);
Beta.GraphServiceClient graphClient = new Beta.GraphServiceClient(authProvider);
var appRoleAssignment = new Beta.AppRoleAssignment
{
AppRoleId = model.appRoleId,
ResourceId = model.resourceId,
ResourceDisplayName = "resourceDisplayName-value",
PrincipalId = model.servicePrincipalId
};
var respone = await graphClient.ServicePrincipals[model.servicePrincipalId].AppRoleAssignments
.Request()
.AddAsync(appRoleAssignment);

Get Azure Roles in the Web App

I created a WebApp in Azure. I have the authentication based on the AzureAD...
Actually all users have the same rights... I need to have a group of Administrators and the rest of the world.
I see that in the Azure Portal for my web app there is a Acces control (IAM) where some roles are listed...
Can I use these roles in my Application?
What actually I do in my View is:
var isAdmin = User.HasClaim("IsAdmin", true.ToString());
If I understand correctly that is named "Claims Based" authentication, but I would like to try to use the Role Based Authentication...
I tried also to do
var userIdentity = (System.Security.Claims.ClaimsIdentity)User.Identity;
var claims = userIdentity.Claims;
var roleClaimType = userIdentity.RoleClaimType;
var roles = claims.Where(c => c.Type == System.Security.Claims.ClaimTypes.Role).ToList();
but that roles list is empty...
Here is the my Startup.cs Autentication code in the public void Configure(IApplicationBuilder app,...
app.UseOpenIdConnectAuthentication(new OpenIdConnectOptions
{
ClientId = Configuration["Authentication:AzureAd:ClientId"],
Authority = Configuration["Authentication:AzureAd:AADInstance"] + Configuration["Authentication:AzureAd:TenantId"],
CallbackPath = Configuration["Authentication:AzureAd:CallbackPath"],
Events = new OpenIdConnectEvents
{
OnTicketReceived = async context =>
{
var user = (ClaimsIdentity)context.Ticket.Principal.Identity;
if (user.IsAuthenticated)
{
var firstName = user.FindFirst(ClaimTypes.GivenName).Value;
var lastName = user.FindFirst(ClaimTypes.Surname).Value;
var email = user.HasClaim(cl => cl.Type == ClaimTypes.Email) ? user.FindFirst(ClaimTypes.Email).Value : user.Name;
var connectedOn = DateTime.UtcNow;
var userId = user.Name;
var myUser = await repository.GetAsync<Connection>(userId);
if (myUser == null)
{
myUser = new Connection(userId)
{
FirstName = firstName,
LastName = lastName,
Email = email
};
}
myUser.LastConnectedOn = connectedOn;
List<Connection> myList = new List<Connection>() { myUser };
var results = await repository.InsertOrMergeAsync(myList);
Claim clm = new Claim("IsAdmin", myUser.IsAdmin.ToString(), ClaimValueTypes.Boolean);
user.AddClaim(clm);
}
return;
}
},
}
});
And also my appsettings.json
"Authentication": {
"AzureAd": {
"AADInstance": "https://login.microsoftonline.com/",
"CallbackPath": "/signin-oidc",
"ClientId": "xxxxxxxx-xxxx-xxxx-xxxxx-xxxxxxxxxxxx",
"Domain": "mysite.azurewebsites.net",
"TenantId": "xxxxxxxx-xxxx-xxxx-xxxxx-xxxxxxxxxxxx"
}
}
I believe that the roles that you observed in the portal are related to the administration of the Web Apps, not the authorization to features it exposes.
To use roles programmatically, I suggest that you look at the following sample which explains how to setup the roles in the Azure AD application corresponding to the project that you deployed as a Web App.
https://github.com/Azure-Samples/active-directory-dotnet-webapp-roleclaims
This way you'll be able to protect pages (from the code in the controller) using attributes:
``
[Authorize(Roles = "Admin, Observer, Writer, Approver")]
See https://github.com/Azure-Samples/active-directory-dotnet-webapp-roleclaims/blob/master/WebApp-RoleClaims-DotNet/Controllers/TasksController.cs#L17
You can also test for users having given roles:
if (User.IsInRole("Admin") || User.IsInRole("Writer"))
{
...
}

Resources