SubscriptionNotFound: The subscription 'resourceGroups' could not be found - c#

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.

Related

EWS API, 401 Unauthorized on BindToItems

I'm struggling with a simple Task, that gets new E-Mails in specific Folders in Exchange Online, sets "Processed"-Category and then stores the E-Mail.
Firstly, I create App permissions like that:
var app = ConfidentialClientApplicationBuilder.Create(_appConfig.ClientId)
.WithAuthority(AzureCloudInstance.AzurePublic,
_appConfig.Tenant)
.WithClientSecret(_appConfig.ClientSecret)
.Build();
AuthenticationResult authResultresult = null;
var ewsScopes = new[] {"https://outlook.office.com/.default"};
authResultresult = await app.AcquireTokenForClient(ewsScopes)
.ExecuteAsync();
then I create Exchange-Client and use created Oauth-Token to authorize:
var result = new ExchangeService(ExchangeVersion.Exchange2013_SP1);
result.KeepAlive = false;
result.DateTimePrecision = DateTimePrecision.Milliseconds;
result.Url = new Uri("https://outlook.office365.com/EWS/Exchange.asmx");
result.UseDefaultCredentials = false;
var authResultresult = await CreateAppPermissions(_appConfig);
result.Credentials = new OAuthCredentials(authResultresult.AccessToken);
after that I impersonate SMTP-User with my mainSMTP account
result.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.SmtpAddress, _appConfig.SMTPMailAccount);
after that I use this Code to retrieve an Email using known Id, add for it new Category and update the item like this:
var itemsToStore = result.BindToItems(new []{newItemId}, props);
foreach (var itemToStore in itemsToStore)
{
itemToStore.Item.Categories.Add("Processed");
itemToStore.Item.Update(ConflictResolutionMode.AlwaysOverwrite, true);
}
This code has previously produced “Access is denied. Check credentials and try again., Cannot save changes made to an item to store." - Exception on Item.Update. After a research I have found this :
Office 365 API ErrorAccessDenied (Access is denied. Check credentials and try again.)
and followed the proposed solution by removing "Have full access to a users mailbox"- checkbox flag.
After that I'm getting 401 unauthorized, when I'm calling BindToItems.
Was it a step backwards to remove the checkbox?
RESOLVED:
Found the solution for 401:
since I'm using EWS a.k.a. older API called Exchange Web Services it was a mistake to remove the checkbox.
the reason for “Access is denied. Check credentials and try again., Cannot save changes made to an item to store." was that impersonated user didn't have rights to change someones elses emails

How to assign a user to an Azure Resource Group

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.

function to search in youtube

I write function for search in youtube.
I create project on "console.developers.google.com" . the name project is youtubesearch and I get apiKey.
I have the error
"An unhandled exception of type
'Google.GData.Client.InvalidCredentialsException' occurred in
Google.GData.Client.dll"
at foreach loop
my code is:
private void getsearch(string serchFor)
{
YouTubeRequestSettings setting = new YouTubeRequestSettings("youtubesearch", "APIkey","ise34857#gmail.com","password for my email");
YouTubeRequest Request = new YouTubeRequest(setting);
YouTubeQuery query = new YouTubeQuery(YouTubeQuery.DefaultVideoUri);
query.OrderBy = "viewCount";
query.Query = serchFor;
query.SafeSearch = YouTubeQuery.SafeSearchValues.Moderate;
Feed<Video> videofeed = Request.Get<Video>(query);
videoLookUp = new Dictionary<string, string>();
foreach (Video v in videofeed.Entries)
{
if (v.Media.Content!=null)
{
Console.WriteLine(v.Title);
Console.WriteLine(v.Media.Content.Url);
comboBox1.Items.Add(v.Title);
videoLookUp.Add(v.Title,v.Media.Content.Url);
}
}
}
Please check object setting if my parameter is right and tell me if I had any proplem in my code
Although the YouTube Data API (v2) has been officially deprecated, you can check in this documentation on how to properly authenticate your application using .NET client library. It also shows here how to properly use the YouTubeRequestSettings object.
To perform any operation using the YouTube API, you create a YouTubeRequestSettings object, which specifies the authentication information and authentication scheme to be used. With that object, you then create a YouTubeRequest object that you will use to actually perform the operations. (If you do not specify authentication information when creating the YouTubeRequestSettings object, then you will only be able to use the YouTubeRequest object to perform operations that do not require authentication.
YouTubeRequestSettings settings =
new YouTubeRequestSettings("example app", clientID, developerKey);
YouTubeRequest request = new YouTubeRequest(settings);
For more information and sample code, check this tutorial.

Error when calling any method on Service Management API

I'm looking to start an Azure runbook from a c# application which will be hosted on an Azure web app.
I'm using certificate authentication (in an attempt just to test that I can connect and retrieve some data)
Here's my code so far:
var cert = ConfigurationManager.AppSettings["mgmtCertificate"];
var creds = new Microsoft.Azure.CertificateCloudCredentials("<my-sub-id>",
new X509Certificate2(Convert.FromBase64String(cert)));
var client = new Microsoft.Azure.Management.Automation.AutomationManagementClient(creds, new Uri("https://management.core.windows.net/"));
var content = client.Runbooks.List("<resource-group-id>", "<automation-account-name>");
Every time I run this, no matter what certificate I use I get the same error:
An unhandled exception of type 'Hyak.Common.CloudException' occurred in Microsoft.Threading.Tasks.dll
Additional information: ForbiddenError: The server failed to authenticate the request. Verify that the certificate is valid and is associated with this subscription.
I've tried downloading the settings file which contains the automatically generated management certificate you get when you spin up the Azure account... nothing I do will let me talk to any of the Azure subscription
Am I missing something fundamental here?
Edit: some additional info...
So I decided to create an application and use the JWT authentication method.
I've added an application, given the application permissions to the Azure Service Management API and ensured the user is a co-administrator and I still get the same error, even with the token...
const string tenantId = "xx";
const string clientId = "xx";
var context = new AuthenticationContext(string.Format("https://login.windows.net/{0}", tenantId));
var user = "<user>";
var pwd = "<pass>";
var userCred = new UserCredential(user, pwd);
var result = context.AcquireToken("https://management.core.windows.net/", clientId, userCred);
var token = result.CreateAuthorizationHeader().Substring("Bearer ".Length); // Token comes back fine and I can inspect and see that it's valid for 1 hour - all looks ok...
var sub = "<subscription-id>";
var creds = new TokenCloudCredentials(sub, token);
var client = new AutomationManagementClient(creds, new Uri("https://management.core.windows.net/"));
var content = client.Runbooks.List("<resource-group>", "<automation-id>");
I've also tried using other Azure libs (like auth, datacentre etc) and I get the same error:
ForbiddenError: The server failed to authenticate the request. Verify that the certificate is valid and is associated with this subscription.
I'm sure it's just 1 tickbox I need to tick buried somewhere in that monolithic Management Portal but I've followed a few tutorials on how to do this and they all end up with this error...
public async Task StartAzureRunbook()
{
try
{
var subscriptionId = "azure subscription Id";
string base64cer = "****long string here****"; //taken from http://stackoverflow.com/questions/24999518/azure-api-the-server-failed-to-authenticate-the-request
var cert = new X509Certificate2(Convert.FromBase64String(base64cer));
var client = new Microsoft.Azure.Management.Automation.AutomationManagementClient(new CertificateCloudCredentials(subscriptionId, cert));
var ct = new CancellationToken();
var content = await client.Runbooks.ListByNameAsync("MyAutomationAccountName", "MyRunbookName", ct);
var firstOrDefault = content?.Runbooks.FirstOrDefault();
if (firstOrDefault != null)
{
var operation = client.Runbooks.Start("MyAutomationAccountName", new RunbookStartParameters(firstOrDefault.Id));
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
Also in portal:
1) Application is multitenant
2) Permissions to other applications section - Windows Azure Service Manager - Delegated permissions "Access Azure Service Management(preview)"
Ensure that your Management certificate has private key and was not made from the .CER file. The fact that you're not supplying a password when generating the X509Certificate object makes me think you're using public key only
Ensure that your Managemnet's certificate public key (.CER file) has been uploaded to the Azure management portal (legacy version, Management Certificate area)
Use CertificateCloudCredentials and not any other credential type of an object
Ok, stupid really but one of the tutorials I followed suggested installing the prerelease version of the libs.
Installing the preview (0.15.2-preview) has fixed the issue!

Google Analytics throws 403 error

I am attempting to download metric data from Google Analytics using C# and am performing user authentication with OAuth 2.0. I'm using the Installed Application authorisation flow, which requires logging into Google and copy-and-pasting a code into the application. I'm following the code taken from google-api-dotnet-client:
private void DownloadData()
{
Service = new AnalyticsService(new BaseClientService.Initializer() {
Authenticator = CreateAuthenticator(),
});
var request = service.Data.Ga.Get(AccountID, StartDate, EndDate, Metrics);
request.Dimensions = Dimensions;
request.StartIndex = 1;
request.MaxResults = 10000;
var response = request.Execute(); // throws Google.GoogleApiException
}
private IAuthenticator CreateAuthenticator()
{
var provider = new NativeApplicationClient(GoogleAuthenticationServer.Description) {
ClientIdentifier = "123456789012.apps.googleusercontent.com",
ClientSecret = "xxxxxxxxxxxxxxxxxxxxxxxx",
};
return new OAuth2Authenticator<NativeApplicationClient>(provider, Login);
}
private static IAuthorizationState Login(NativeApplicationClient arg)
{
// Generate the authorization URL.
IAuthorizationState state = new AuthorizationState(new[] { AnalyticsService.Scopes.AnalyticsReadonly.GetStringValue() });
state.Callback = new Uri(NativeApplicationClient.OutOfBandCallbackUrl);
Uri authUri = arg.RequestUserAuthorization(state);
// Request authorization from the user by opening a browser window.
Process.Start(authUri.ToString());
Console.Write("Google Authorization Code: ");
string authCode = Console.ReadLine();
// Retrieve the access token by using the authorization code.
state = arg.ProcessUserAuthorization(authCode, state);
return state;
}
The Google account xxxxxx#gmail.com registered the Client ID and secret. The same account has full administration rights in Google Analytics. When I try to pull data from Google Analytics, it goes through the authorisation process, which appears to work properly. Then it fails with:
Google.GoogleApiException
Google.Apis.Requests.RequestError
User does not have sufficient permissions for this profile. [403]
Errors [
Message[User does not have sufficient permissions for this profile.] Location[ - ] Reason [insufficientPermissions] Domain[global]
]
I've been struggling with this for a few hours. I've double checked that the correct user is being used, and is authorised on Google Analytics. I'm at a loss as to what is misconfigured. Any ideas as to what requires configuring or changing?
If auth seems to be working working then my suggestion is that you make sure you're providing the correct ID because based on your code snippet:
var request = service.Data.Ga.Get(AccountID, StartDate, EndDate, Metrics);
one can only assume that you're using the Account ID. If so, that is incorrect and you'd receive the error you've encountered. You need to query with the Profile ID.
If you login to Google Analytics using the web interface you'll see the following pattern in URL of the browser's address bar:
/a12345w654321p9876543/
The number following the p is the profile ID, so 9876543 in the example above. Make sure you're using that and actually you should be using the table id which would be ga:9876543.
If it isn't an ID issue then instead query the Management API to list accounts and see what you have access to and to verify auth is working correctly.
This can help : https://developers.google.com/analytics/devguides/reporting/core/v3/coreErrors, look error 403.
//Thanks for this post. The required profile id can be read from the account summaries.
Dictionary profiles = new Dictionary();
var accounts = service.Management.AccountSummaries.List().Execute();
foreach (var account in accounts.Items)
{
var profileId = account.WebProperties[0].Profiles[0].Id;
profiles.Add("ga:" + profileId, account.Name);
}

Categories

Resources