Query Azure Compute Quotas from .NET SDK - azure-sdk-.net

I am looking for examples of how to use the Azure .NET SDK to query for the current usage and remaining quotas for Compute resources (say Dsv3 vCPUs).
Thanks!

According to my test, we can use Azure .Net SDK Microsoft.Azure.Management.Compute.Fluent to list the usage of Microsoft.Comput resource in one Azure Subscription. For more details, please refer to the document
Use Azure CLI to create a service pricipal
az login
az ad sp create-for-rbac --name <ServicePrincipalName>
az role assignment create --assignee <ServicePrincipalName> --role Contributor
Code
var tenantId = "<your tenant id>";
var clientId = "<your sp app id> ";
var clientSecret = "<your sp passowrd>";
var subscriptionId = "<your subscription id>";
AzureCredentials credentials = SdkContext.AzureCredentialsFactory.FromServicePrincipal(
clientId,
clientSecret,
tenantId,
AzureEnvironment.AzureGlobalCloud);
RestClient restClient = RestClient.Configure()
.WithEnvironment(AzureEnvironment.AzureGlobalCloud)
.WithCredentials(credentials)
.WithLogLevel(HttpLoggingDelegatingHandler.Level.Basic)
.Build();
ComputeManagementClientclient = new ComputeManagementClient(restClient);
client.SubscriptionId = subscriptionId;
foreach (var s1 in await UsageOperationsExtensions.ListAsync(client.Usage, Region.AsiaSouthEast.Name)) {
Console.WriteLine("Name: " + s1.Name.LocalizedValue +"\nUnit: "+ UsageInner.Unit + "\nCurrentValue: " + s1.CurrentValue + "\nLimit: " + s1.Limit);
Console.WriteLine("-----------------------");
}

Related

Authorization has been denied for this request while integrating Identity server4 (ver 3.0.0) token into Microsoft.AspNet.WebApi (Framework 4.6.2)"

I am using Identity server4 (ver 3.0.0) and want to authenticate Microsoft.AspNet.WebApi " version="5.2.7" targetFramework="net462"
I have installed identity server3 in AspNet.WebApi project.While I am authenticating .net web api request using Bearer token
that i got from identity server4.this showing me unAuthorized Access. I am attaching some screenshots here :
Postman Screenshot:
https://prnt.sc/qu0sb6
Blockquote
public void Configuration(IAppBuilder app)
{
HttpConfiguration webApiConfig = new HttpConfiguration();
webApiConfig.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;
app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
app.Use<ExceptionHandler>();
ConfigureAuth(app);
app.UseIdentityServerBearerTokenAuthentication(new IdentityServerBearerTokenAuthenticationOptions
{
Authority = "https://localhost:44353/",
ClientId = "ConsoleApp_ClientId",
ClientSecret = "secret_for_the_consoleapp",
RequiredScopes = new[] { "SmarttrackReportAPI" },
DelayLoadMetadata = true
});
app.Use<SessionAuthenticator>();
WebApiConfig.Register(webApiConfig);
HttpServer webApiServer = new HttpServer(webApiConfig);
app.UseWebApi(webApiServer);
}
Installed package Screenshot:
https://prnt.sc/qu0sv1
Please help.

Keycloak java client 403 when retrieving role detail

I'm working with keycloak 8.0.1 and it's java client keycloak-admin-client library.
this is my Keycloak config
public Keycloak keycloakClient(AdapterConfig config) {
return KeycloakBuilder.builder()
.clientId(config.getResource())
.clientSecret((String) config.getCredentials().get(CredentialRepresentation.SECRET))
.grantType(OAuth2Constants.CLIENT_CREDENTIALS)
.realm(config.getRealm())
.serverUrl(config.getAuthServerUrl())
.build();
}
And with this code I'd like to create user and assign him a role
final UserRepresentation user = createUserRepresentation(data);
final UsersResource userResource = getRealmResource().users();
try (Response response = userResource.create(user)) {
if (response.getStatusInfo().getFamily().equals(Response.Status.Family.SUCCESSFUL)) {
final String userId = response.getLocation().getPath().replaceAll(".*/([^/]+)$", "$1");
final RolesResource rolesResource = getRealmResource().roles();
final RoleResource roleResource = rolesResource.get(data.getRole().getRemoteName());
final RoleRepresentation role = roleResource.toRepresentation();
userResource.get(userId).roles().realmLevel().add(Collections.singletonList(role));
return userId;
} else {
throw new IllegalStateException("Unable to create user " + response.getStatusInfo().getReasonPhrase());
}
}
however it fails on line final RoleRepresentation role = roleResource.toRepresentation(); with message javax.ws.rs.ForbiddenException: HTTP 403 Forbidden.
I don't understand why am I getting this error, because my client has assigned all roles from realm-management client
create-client
impersonation
manage-authorization
manage-clients
manage-events
manage-identity-providers
manage-realm
manage-users
query-clients
query-groups
query-realms
query-users
realm-admin
view-authorization
view-clients
view-events
view-identity-providers
view-realm
view-users
Is there some config which am I missing or is it a bug?
Thanks
I just have the same problem here, while I'm trying to assign roles to an existing user using a service client (using client credentials).
The solution:
Go to Clients > Select "your" client > Go to "Service Account Roles" Tab > Select Client Roles : "realm-management" and add "view-realm" into the assigned roles.
That's it :)

VSTS - Getting al Team Project Administrators using VSTS REST API

Is it possible to get all project administrators per project? I found out I can get all projects and their team members using this API: https://www.visualstudio.com/en-us/docs/integrate/api/tfs/teams#get-a-teams-members
But then I get a full list of members of the Team Project, and not their permissions. I want to have a list of administrators, so that I can contact them about their TeamProject.
Thanks in advance!
BTW, using TFS 2017
There is no such REST API to get members from a VSTS group (such as Project Administrators) for now.
But there has an user voice REST API for a better Projects and Team Management which contains similar function in the suggestions, you can vote and follow up.
It cannot be achieved via Rest API, but it can be achieved with SOAP API. Following is the code sample for your reference:
using System;
using Microsoft.TeamFoundation.Client;
using Microsoft.TeamFoundation.Framework.Client;
using Microsoft.TeamFoundation.Framework.Common;
namespace GetAdmin
{
class Program
{
static void Main(string[] args)
{
string projectname = "projectname";
string groupname = $"[{projectname}]\\Project Administrators";
TfsTeamProjectCollection ttpc = new TfsTeamProjectCollection(new Uri("https://vstsaccount.visualstudio.com/"));
IIdentityManagementService idms = ttpc.GetService<IIdentityManagementService>();
TeamFoundationIdentity admingroup = idms.ReadIdentity(IdentitySearchFactor.AccountName,groupname,MembershipQuery.Direct,ReadIdentityOptions.IncludeReadFromSource);
foreach (IdentityDescriptor tfi in admingroup.Members)
{
TeamFoundationIdentity member = idms.ReadIdentity(tfi,MembershipQuery.Expanded, ReadIdentityOptions.ExtendedProperties);
Console.WriteLine(member.DisplayName);
Console.WriteLine(member.GetProperty("Mail"));
}
Console.ReadLine();
}
}
}
Powershell Script:
$dllpath1 = "D:\\net45\\Microsoft.TeamFoundation.Client.dll";
$dllpath2 = "D:\\net45\\Microsoft.TeamFoundation.Common.dll";
$dllpath3 = "D:\\net45\\Microsoft.VisualStudio.Services.Common.dll";
$dllpath4 = "D:\\net45\\Microsoft.VisualStudio.Services.Client.Interactive.dll";
[System.Reflection.Assembly]::LoadFrom($dllpath1);
[System.Reflection.Assembly]::LoadFrom($dllpath2);
[System.Reflection.Assembly]::LoadFrom($dllpath3);
[System.Reflection.Assembly]::LoadFrom($dllpath4);
$uri = "https://xxx.visualstudio.com/";
$tfs = [Microsoft.TeamFoundation.Client.TfsTeamProjectCollectionFactory]::GetTeamProjectCollection($uri)
$idservice = $tfs.GetService("Microsoft.TeamFoundation.FrameWork.Client.IIdentityManagementService")
$projectname = "xxx"
$groupname = "[" + $projectname + "]\Project Administrators";
$admingroup = $idservice.ReadIdentity([Microsoft.TeamFoundation.FrameWork.Common.IdentitySearchFactor]::AccountName,$groupname,[Microsoft.TeamFoundation.FrameWork.Common.MembershipQuery]::Direct,[Microsoft.TeamFoundation.FrameWork.Common.ReadIdentityOptions]::IncludeReadFromSource)
foreach ($id in $admingroup.Members)
{
$member = $idservice.ReadIdentity($id,[Microsoft.TeamFoundation.FrameWork.Common.MembershipQuery]::Expanded, [Microsoft.TeamFoundation.FrameWork.Common.ReadIdentityOptions]::ExtendedProperties)
Write-Host $member.DisplayName
Write-Host $member.GetProperty("Mail")
}

KeyVault generated certificate with exportable private key

I'm attempting to create a self signed certificate in KeyVault using the "Self" issuer.
$policy = New-AzureKeyVaultCertificatePolicy -SubjectName "CN=$($certificateName)" -IssuerName "Self" -ValidityInMonths 12
$policy.Exportable = $true
Add-AzureKeyVaultCertificate -VaultName $vaultName -Name $certificateName -CertificatePolicy $policy
However, when getting the certificate back it doesn't appear to have a private key.
Creating certificates directly in KeyVault doesn't seem hugely covered online, after digging into the rest API documentation and source code for the powershell cmdlets, I'm stumped.
I'm hoping it's something simple I've missed, as I wish to avoid creating the certificate locally..
If you'd like to retrieve your certificate along with its private key, then you can export it to a PFX file (with an empty password) on your disk via:
$vaultName = "my-vault-name"
$certificateName = "my-cert-name"
$pfxPath = [Environment]::GetFolderPath("Desktop") + "\$certificateName.pfx"
$pfxSecret = Get-AzureKeyVaultSecret -VaultName $vaultName -Name $certificateName
$pfxUnprotectedBytes = [Convert]::FromBase64String($pfxSecret.SecretValueText)
[IO.File]::WriteAllBytes($pfxPath, $pfxUnprotectedBytes)
If you'd like to view just the private key itself in-memory without writing to disk, then try:
$vaultName = "my-vault-name"
$certificateName = "my-cert-name"
$pfxPath = [Environment]::GetFolderPath("Desktop") + "\$certificateName.pfx"
$pfxSecret = Get-AzureKeyVaultSecret -VaultName $vaultName -Name $certificateName
$pfxUnprotectedBytes = [Convert]::FromBase64String($pfxSecret.SecretValueText)
$pfx = New-Object Security.Cryptography.X509Certificates.X509Certificate2
$pfx.Import($pfxUnprotectedBytes, $null, [Security.Cryptography.X509Certificates.X509KeyStorageFlags]::Exportable)
$pfx.PrivateKey.ExportParameters($true)
which will show the private parameters in addition to the exponent and modulus.
If you'd like to protect the PFX file on disk with your own password (as per the "Retrieve pfx file & add password back" instructions in this blog post), then try:
$vaultName = "my-vault-name"
$certificateName = "my-cert-name"
$pfxPath = [Environment]::GetFolderPath("Desktop") + "\$certificateName.pfx"
$password = "my-password"
$pfxSecret = Get-AzureKeyVaultSecret -VaultName $vaultName -Name $certificateName
$pfxUnprotectedBytes = [Convert]::FromBase64String($pfxSecret.SecretValueText)
$pfx = New-Object Security.Cryptography.X509Certificates.X509Certificate2
$pfx.Import($pfxUnprotectedBytes, $null, [Security.Cryptography.X509Certificates.X509KeyStorageFlags]::Exportable)
$pfxProtectedBytes = $pfx.Export([Security.Cryptography.X509Certificates.X509ContentType]::Pkcs12, $password)
[IO.File]::WriteAllBytes($pfxPath, $pfxProtectedBytes)
As mentioned in the REST API docs here and here, Azure Key Vault (AKV) represents a given X.509 certificate via three interrelated resources: an AKV-certificate, an AKV-key, and an AKV-secret. All three will share the same name and the same version - to verify this, examine the Id, KeyId, and SecretId properties in the response from Get-AzureKeyVaultCertificate.
Each of these 3 resources provide a different perspective for viewing a given X.509 cert:
The AKV-certificate provides the public key and cert metadata of the X.509 certificate. It contains the public key's modulus and exponent (n and e), as well as other cert metadata (thumbprint, expiry date, subject name, and so on). In PowerShell, you can obtain this via:
(Get-AzureKeyVaultCertificate -VaultName $vaultName -Name $certificateName).Certificate
The AKV-key provides the private key of the X.509 certificate. It can be useful for performing cryptographic operations such as signing if the corresponding certificate was marked as non-exportable. In PowerShell, you can only obtain the public portion of this private key via:
(Get-AzureKeyVaultKey -VaultName $vaultName -Name $certificateName).Key
The AKV-secret provides a way to export the full X.509 certificate, including its private key (if its policy allows for private key exporting). As demonstrated above, the current base64-encoded certificate can be obtained in PowerShell via:
(Get-AzureKeyVaultSecret -VaultName $vaultName -Name $certificateName).SecretValueText
Following is C# code to retrieve all versions of a certificate, including their private keys, from newest to oldest, given its certificate name and KeyVault connection info. It uses the new Azure.Core, Azure.Identity, and Azure.Security.KeyVault.[Certificates|Secrets] SDK packages.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using Azure.Core;
using Azure.Identity;
using Azure.Security.KeyVault.Certificates;
using Azure.Security.KeyVault.Secrets;
public static class CertTools
{
public static void MyMethod(string tenantId, string clientId, string clientSecret, Uri keyVaultUri)
{
var cred = new ClientSecretCredential(tenantId, clientId, clientSecret); // or any other means of obtaining Azure credential
var certs = GetAllCertificateVersions(keyVaultUri, cred, "MyCert");
}
public static List<X509Certificate2> GetAllCertificateVersions(Uri keyVaultUri, TokenCredential credential,
string certificateName)
{
var certClient = new CertificateClient(keyVaultUri, credential);
var secretClient = new SecretClient(keyVaultUri, credential);
var now = DateTimeOffset.UtcNow;
var certs = new List<X509Certificate2>();
foreach (var cert in certClient.GetPropertiesOfCertificateVersions(certificateName)
.OrderByDescending(x => x.CreatedOn)
// fetch all enabled, non-expired certificates. adjust this predicate if desired.
.Where(x => x.ExpiresOn >= now && (x.Enabled ?? false)))
{
var secret = secretClient.GetSecret(certificateName, cert.Version).Value;
certs.Add(new X509Certificate2(Convert.FromBase64String(secret.Value)));
}
return certs;
}
}
Thanks to #Nandun's answer here for pointing me in the right direction of using the SecretClient instead of CertificateClient, but that post was marked as a duplicate so posting this extended code here.

couldnot get access token for daemon applications office 365

I have followed the blog http://blogs.msdn.com/b/exchangedev/archive/2015/01/22/building-demon-or-service-apps-with-office-365-mail-calendar-and-contacts-apis-oauth2-client-credential-flow.aspx to create a daemon application . I am able to get the app only token for the domain in which i have registered the application . But when I try to get for other organizations it throws an error
"
{"error":"invalid_client","error_description":"AADSTS70002: Error validating cre
dentials. AADSTS50012: Client assertion audience claim does not match Realm issu
er.\r\nTrace ID: 09e025f5-7db9-46c3-9df9-574c6820a011\r\nCorrelation ID: f4d0fa5
7-ee8c-4443-b28b-d372d945f81f\r\nTimestamp: 2015-05-04 13:51:51Z","error_codes":
[70002,50012],"timestamp":"2015-05-04 13:51:51Z","trace_id":"09e025f5-7db9-46c3-
9df9-574c6820a011","correlation_id":"f4d0fa57-ee8c-4443-b28b-d372d945f81f","subm
it_url":null,"context":null}"
But i have configured the application to be multi tenant .
this is the request i make
request https://login.windows.net/<tenantId>/oauth2/to
ken
grant_type=client_credentials
redirect_uri=http://localhost.com:9000
resource=https://outlook.office365.com/
client_assertion_type =urn:ietf:params:oauth:client-assertion-type:jwt-bearer
client_assertion="eyJhbGciOiJSUzI1NiIsIng1dCI6IjZlLzEra01scHhuTHArZFJ4d1BqS21EdmZCQT0ifQ.eyJhdWQiOiJodHRwczovL2xvZ2luLndpbmRvd3MubmV0L2ZmNjQxNTFmLTIwM2EtNGM0MC1hZDcxLTExOTE2YjY2Yzg3My9vYXV0aDIvdG9rZW4iLCJleHAiOjE0MzEwMDYzMDMsImlzcyI6ImFkMTkzY2I1LWU2NmUtNDdmNS1iMTc4LTQxM2NlODA3ZDg2YiIsImp0aSI6IjMyMDZiYWI5LTVmYmUtNDA3ZS02OWY2LTJlNGRjNDQ3NzQxYSIsIm5iZiI6MTQzMTAxMTMwMywic3ViIjoiYWQxOTNjYjUtZTY2ZS00N2Y1LWIxNzgtNDEzY2U4MDdkODZiIn0.eEOlhsl-vbdzIiV3AfGFOH187Yb8zpGSGm6RbMhDX4NRJbwOWjJr3eFK3rGXSkl1vhSfJ_oFc69pB1AGfUK8u_SWRl7U3GgH3EJryE-FiVluCQ-ONZ3Qj1u6VggXgTodi0bdvhQF4WlwazXmJGbpeVRUZBm2rlTcd8JtQY96sOu1CRDpZJOFnHzjqleVdrnw8_pNVUafwlnaosRT9tOIgiK9apjN_KY5JMM1QTYKhKk5ZApjmr8agTZpObdz-_Y9znjaSxQcYkFnQeCGc-qwISzH1OqG_7JbCDq6Dp1-oBU5sJneJaF6IxX8-sWyaju3ntMWQyINeuHnRCoPrlp2tg"
this is the assertion i create
token.Header["alg"] = "RS256"
token.Header["x5t"] = "thumbprint of certificate "
token.Claims["aud"] = "https://login.windows.net/" + TenantId + "/oauth2/token"
token.Claims["exp"] = time.Now().Add(time.Hour * 72).Unix()
token.Claims["iss"] = client_id
token.Claims["jti"] = some guid
token.Claims["nbf"] = (time.Now().Add(time.Hour * 72).Unix()) + 5000
token.Claims["sub"] = client_id
please let me what to be done so that i can get the access token for other organiztion's domain .
Thanks in advance