Azure Autoscaling (400) Bad Request - azure

I try to increase my instance count by code behind.
First of all I created one .cer file and .pfx file and I upload it into .pfx to cloudservice certificates and .cer to settings --> management certificates.
After I used .cer file in my code. I don't know very well this uplod file is it true ?
Here is my code :
string subscriptionId = "c034e905-......";
string serviceName = "multitenant";
string configFileName = "ServiceConfiguration.cscfg";
string roleName = "Multi.Web";
XNamespace xs = "http://schemas.microsoft.com/ServiceHosting/2008/10/ServiceConfiguration";
XDocument configDocument = XDocument.Parse(String.Join("", File.ReadAllLines(Path.GetFullPath(configFileName))));
XAttribute instanceCountAttribute = configDocument.Element(xs + "ServiceConfiguration")
.Elements(xs + "Role")
.Where(xRole => xRole.Attribute("name").Value == roleName).SingleOrDefault()
.Element(xs + "Instances")
.Attribute("count");
int currentInstanceCount = int.Parse(instanceCountAttribute.Value);
and I am checking some fields in my VM and I incease my currentInstanceCount .
double processorTotal = Convert.ToDouble(performanceCounter.CounterValue);
instanceCountAttribute.Value = (currentInstanceCount + 1).ToString();
var serviceManagment = ServiceManagementHelper.CreateServiceManagementChannel("WindowsAzureEndPoint",
new X509Certificate2("multitenant.cer"));
var changeConfigInput = new ChangeConfigurationInput();
changeConfigInput.Configuration = ServiceManagementHelper.EncodeToBase64String(configDocument.ToString());
try
{
serviceManagment.ChangeConfigurationBySlot(subscriptionId, serviceName, "Production", changeConfigInput);
}
catch (WebException e)
{
throw new Exception(new StreamReader(e.Response.GetResponseStream()).ReadToEnd());
}
ChangeConfigurationBySlot method is throwing exception :
The remote server returned an unexpected response: (400) Bad Request.
Where am I wrong ? I couldn't understand. Is it about method parameters or wrong upload certificate ?
Do you have any estimate?
Thanks.

I solved my problem.
It is not about certification.First I get the production configuration file and I change it's current instance count and redeploy.
Here is the code :
var deployment = managementClient.GetDeploymentBySlot(subscriptionId, serviceName, "Production");
string configurationXml = ServiceManagementHelper.DecodeFromBase64String(deployment.Configuration);
serviceConfiguration = XDocument.Parse(configurationXml);
XNamespace xs = "http://schemas.microsoft.com/ServiceHosting/2008/10/ServiceConfiguration";
instanceCountAttribute = serviceConfiguration.Element(xs + "ServiceConfiguration")
.Elements(xs + "Role")
.Where(xRole => xRole.Attribute("name").Value == roleName).SingleOrDefault()
.Element(xs + "Instances")
.Attribute("count");
currentInstanceCount = int.Parse(instanceCountAttribute.Value);

Related

Authentication Failure when uploading to Azure Blob Storage using Azure.Storage.Blob v12.9.0

I get this error when trying to upload files to blob storage. The error is present both when I run on localhost and when I run in Azure Function.
My connection string looks like:
DefaultEndpointsProtocol=https;AccountName=xxx;AccountKey=xxx;EndpointSuffix=core.windows.net
Authentication information is not given in the correct format. Check the value of the Authorization header.
Time:2021-10-14T15:56:26.7659660Z
Status: 400 (Authentication information is not given in the correct format. Check the value of Authorization header.)
ErrorCode: InvalidAuthenticationInfo
But this used to work in the past but recently its started throwing this error for a new storage account I created. My code looks like below
public AzureStorageService(IOptions<AzureStorageSettings> options)
{
_connectionString = options.Value.ConnectionString;
_containerName = options.Value.ImageContainer;
_sasCredential = new StorageSharedKeyCredential(options.Value.AccountName, options.Value.Key);
_blobServiceClient = new BlobServiceClient(new BlobServiceClient(_connectionString).Uri, _sasCredential);
_containerClient = _blobServiceClient.GetBlobContainerClient(_containerName);
}
public async Task<string> UploadFileAsync(IFormFile file, string location, bool publicAccess = true)
{
try
{
await _containerClient.CreateIfNotExistsAsync(publicAccess
? PublicAccessType.Blob
: PublicAccessType.None);
var blobClient = _containerClient.GetBlobClient(location);
await using var fileStream = file.OpenReadStream();
// throws Exception here
await blobClient.UploadAsync(fileStream, true);
return blobClient.Uri.ToString();
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
}
// To be able to do this, I have to create the container client via the blobService client which was created along with the SharedStorageKeyCredential
public Uri GetSasContainerUri()
{
if (_containerClient.CanGenerateSasUri)
{
// Create a SAS token that's valid for one hour.
var sasBuilder = new BlobSasBuilder()
{
BlobContainerName = _containerClient.Name,
Resource = "c"
};
sasBuilder.ExpiresOn = DateTimeOffset.UtcNow.AddHours(1);
sasBuilder.SetPermissions(BlobContainerSasPermissions.Write);
var sasUri = _containerClient.GenerateSasUri(sasBuilder);
Console.WriteLine("SAS URI for blob container is: {0}", sasUri);
Console.WriteLine();
return sasUri;
}
else
{
Console.WriteLine(#"BlobContainerClient must be authorized with Shared Key
credentials to create a service SAS.");
return null;
}
}
Please change the following line of code:
_blobServiceClient = new BlobServiceClient(new BlobServiceClient(_connectionString).Uri, _sasCredential);
to
_blobServiceClient = new BlobServiceClient(_connectionString);
Considering your connection string has all the necessary information, you don't really need to do all the things you're doing and you will be using BlobServiceClient(String) constructor which expects and accepts the connection string.
You can also delete the following line of code:
_sasCredential = new StorageSharedKeyCredential(options.Value.AccountName, options.Value.Key);
and can probably get rid of AccountName and Key from your configuration settings if they are not used elsewhere.

Cache Token on Azure Functions (3rd party Token)

I am using HTTP Trigger Azure Functions for getting/posting data on a third party API service. This API service needs firstly to authenticate and then get a Token for using another service. So , I want to cache the token. Problem is that once I deploy to Azure, it asks me for an "empty paramter" called S. Strange as it sounds. Every advice is welcome. Thanks! Cache code is :
/*
object cacheKeyDefault = MemoryCache.Default.Get($"{userId+usuario + canal + device}");
if (cacheKeyDefault == null)
{
//Genero póliza con el tiempo obtenido del Environment
CacheItemPolicy cip = new CacheItemPolicy()
{
AbsoluteExpiration = new DateTimeOffset(DateTime.Now.AddHours(double.Parse(tokenTimeout)))
};
//Genero Json de request para Token
RequestToken tokenRequest = JsonConvert.DeserializeObject<RequestToken>(requestBody);
string tokenrequestJs = JsonConvert.SerializeObject(tokenRequest);
log.LogInformation($"tokenrequestJs: {tokenrequestJs} ");
//Obtengo el Session Token
string responseTokenJs = RestAPI.Ejecutar(url + accionToken, Method.POST, tokenrequestJs);
log.LogInformation("Response Token: " + responseTokenJs);
//Lo agrego dinámicamente
dynamic tokenResponseDynamic = JsonConvert.DeserializeObject(responseTokenJs);
dynamic SessionToken = tokenResponseDynamic.SessionToken;
string SessionTokenString = SessionToken;
reqBody.Btinreq.Token = SessionToken;
MemoryCache.Default.Set($"{userId+usuario +canal+device}", SessionTokenString, cip);
}
else
{
dynamic SessionToken = cacheKeyDefault;
reqBody.Btinreq.Token = SessionToken;
}

ShareSasBuilder generating an invalid signature

I'm trying to generate a SAS signed URL to download a file from an Azure file storage (using this as an example):
using Azure.Storage;
using Azure.Storage.Files.Shares;
using Azure.Storage.Files.Shares.Models;
using Azure.Storage.Sas;
(...)
public Uri getFileUri(string fileName)
{
string AccountName = WebConfigurationManager.AppSettings["AzureStorageDepotAccountName"];
string AccountKey = WebConfigurationManager.AppSettings["AzureStorageDepotAccountKey"];
sharedKeyCredential = new StorageSharedKeyCredential(AccountName, AccountKey);
shareClient = new ShareClient(new Uri("https://sanitizedShare.file.core.windows.net/"), sharedKeyCredential);
ShareDirectoryClient directory = shareClient.GetDirectoryClient("sanitizedDir");
ShareFileClient file = directory.GetFileClient(fileName);
var shareSasBuilder = new ShareSasBuilder
{
ShareName = "sanitizedShare",
FilePath = file.Uri.LocalPath,
Protocol = SasProtocol.None,
StartsOn = DateTime.UtcNow.AddHours(-1),
ExpiresOn = DateTime.UtcNow.AddHours(+2),
IPRange = new SasIPRange(IPAddress.None, IPAddress.None)
};
shareSasBuilder.SetPermissions(ShareFileSasPermissions.Read);
return new Uri(file.Uri + "?" + shareSasBuilder.ToSasQueryParameters(sharedKeyCredential).ToString());
}
It returns a correct looking URL (https://sanitizedShare.file.core.windows.net/sanitizedDir/sanitizedFile?sv=2019-07-07&st=2020-05-27T19:36:55Z&se=2020-05-27T22:36:55Z&sr=f&sp=r&sig=l3bLiYlA9Y+Se1jC1g/F5A0T4yOT0nUJHUxyLhNksw8=) but when I try it I get this error:
<Error>
<Code>AuthenticationFailed</Code>
<Message>
Server failed to authenticate the request. Make sure the value of Authorization header is formed correctly including the signature. RequestId:8c400781-e01a-0040-4266-347d43000000 Time:2020-05-27T20:36:56.2303652Z
</Message>
<AuthenticationErrorDetail>Signature fields not well formed.</AuthenticationErrorDetail>
</Error>
At first I thought that I had the wrong credentials, but I'm using the same credentials elsewhere in my code and it can access the share. Do you know what the problem could be?
Make the following changes to your code:
1.add the file share name at the end of the url when create the ShareClient(Note:for the url, I see you're using fileshareName.file.core.windows.net, it should be your_storage_account_name.file.core.windows.net), like below:
var shareClient = new ShareClient(new Uri("https://your_storage_account_name.file.core.windows.net/the_share_name"), sharedKeyCredential);
2.in the code block of new ShareSasBuilder{}, remove FilePath = file.Uri.LocalPath,
Then I tested the code(with the latest version of Azure.Storage.Files.Shares 12.2.1), it generates a valid and working url with sastoken. My code as below:
string storageAccount= "yy1";
string password = "xxxx";
var sharedKeyCredential = new StorageSharedKeyCredential(storageAccount, password);
//the file share name is aaa
var shareClient = new ShareClient(new Uri("https://yy1.file.core.windows.net/aaa"), sharedKeyCredential);
ShareDirectoryClient directory = shareClient.GetDirectoryClient("a11");
ShareFileClient file = directory.GetFileClient("1.txt");
var shareSasBuilder = new ShareSasBuilder
{
ShareName = "aaa",
//FilePath = file.Uri.LocalPath,
Protocol = SasProtocol.None,
StartsOn = DateTime.UtcNow.AddHours(-1),
ExpiresOn = DateTime.UtcNow.AddHours(+2),
IPRange = new SasIPRange(IPAddress.None, IPAddress.None)
};
shareSasBuilder.SetPermissions(ShareFileSasPermissions.Read);
var url = new Uri(file.Uri + "?" + shareSasBuilder.ToSasQueryParameters(sharedKeyCredential).ToString());

Windows Azure Cloud App - Could not create SSL/TLS secure channel

I am trying to pull JSON from a customer's website, but I get this error.
The code works my local machine.
For other sites, both on my local machine and on the server, the code works.
The site is https://www.vapedepot.ca/wc-api/v1
Does he have a special SSL cert where I need to change my code? Here is my code:
string GetJson(string url)
{
string resultData = string.Empty;
HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create(url);
myHttpWebRequest.Accept = "application/json";
myHttpWebRequest.Timeout = 6000;
//myHttpWebRequest.ContentType = "application/x-www-form-urlencoded";
string userP = m_UserName + ":" + m_Password;
byte[] authBytes = Encoding.UTF8.GetBytes(userP).ToArray();
myHttpWebRequest.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(authBytes));
WebResponse httpResponse = myHttpWebRequest.GetResponse();
Stream responseStream = httpResponse.GetResponseStream();
StreamReader reader = new StreamReader(responseStream);
resultData = reader.ReadToEnd();
responseStream.Close();
httpResponse.Close();
return resultData;
}
He is using CloudFlare and the SSL uses ecdsa.
I had the same issue. I swapped to using RestSharp to make my secure web requests and it resolved my issue.

ADFS 2.0 custom login page implementation - "The request scope is not valid or is not supported"

I am trying to work out how to set up my SharePoint 2013 to use a custom login page to login through ADFS 2.0 instead of the standard one.
I am following this tutorial: http://blog.helloitsliam.com/Lists/Posts/Post.aspx?ID=76
After making the changes to web.config I have written the following code to my page:
using (var wsFactory = new WSTrustChannelFactory(new UserNameWSTrustBinding(SecurityMode.TransportWithMessageCredential), new EndpointAddress(endpoint)))
{
wsFactory.Credentials.UserName.UserName = signInControl.UserName;
wsFactory.Credentials.UserName.Password = signInControl.Password;
wsFactory.TrustVersion = TrustVersion.WSTrust13;
var wsChannel = wsFactory.CreateChannel();
var requestSecurityToken = new RequestSecurityToken { RequestType = RequestTypes.Issue, AppliesTo = new EndpointReference(AppliesToEndpointUrl), KeyType = KeyTypes.Symmetric };
try
{
var genericSecurityToken = wsChannel.Issue(requestSecurityToken) as GenericXmlSecurityToken;
var securityTokenHandlers = FederatedAuthentication.ServiceConfiguration.SecurityTokenHandlers;
var securityToken = securityTokenHandlers.ReadToken(new XmlTextReader(new StringReader(genericSecurityToken.TokenXml.OuterXml)));
SPSecurity.RunWithElevatedPrivileges(() =>
Microsoft.SharePoint.IdentityModel.SPFederationAuthenticationModule.Current.SetPrincipalAndWriteSessionToken(securityToken));
var rUrl = Request.QueryString.Get("Source");
Response.Redirect(String.IsNullOrEmpty(rUrl) ? "~/Pages/Default.aspx" : rUrl);
}
catch (Exception ex)
{
Response.Write(ex.StackTrace);
}
The debugger throws the following error on the wsChannel.Issue method invocation:
ID3082: The request scope is not valid or is unsupported.
Now, how should I investigate the cause of such error?

Resources