Unable to retrieve API keys for a Function App using ListWebAppFunctionKeysArgs - pulumi

How can I retrieve API keys for a function app in Azure using ListWebAppFunctionKeysArgs?
I have the following method:
public static Output<Dictionary<string, string>?> Get(string resourceGroupName, FunctionApp functionApp)
{
var output =
Output.Tuple(functionApp.Name, functionApp.Name)
.Apply(async tuple => {
var current = Pulumi.Azure.Core.GetClientConfig.InvokeAsync().Result;
var subscriptionId = current.SubscriptionId;
var appName = tuple.Item1;
var httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", AuthToken.Value);
var url = $"https://management.azure.com/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/sites/{appName}/functions?api-version=2022-03-01";
var result = await httpClient.GetAsync(url);
if (!result.IsSuccessStatusCode) throw new Exception($"Error: Failed to retrive Azure function names from {appName}");
var json = await result.Content.ReadAsStringAsync();
var root = JsonConvert.DeserializeObject<JsonSupport.AzureFunctionItems.Root>(json);
var items = root.value.Select(async v => {
var data = await ListWebAppFunctionKeys.InvokeAsync(new ListWebAppFunctionKeysArgs {
Name = appName,
FunctionName = v.properties.name,
ResourceGroupName = resourceGroupName
});
return data.Properties;
});
var data = items.SelectMany(v => v.Result).ToList();
return new Dictionary<string, string>(data);
});
return output;
}
Here's the code that I'm struggling with:
var json = await result.Content.ReadAsStringAsync();
var root = JsonConvert.DeserializeObject<JsonSupport.AzureFunctionItems.Root>(json);
var items = root.value.Select(async v => {
var data = await ListWebAppFunctionKeys.InvokeAsync(new ListWebAppFunctionKeysArgs {
Name = appName,
FunctionName = v.properties.name,
ResourceGroupName = resourceGroupName
});
return data.Properties; // Property values are null
});
Here's the result:
In conclusion, how do I acquire API keys for a function app?

Related

SageMaker API Header signature issue in flutter

here is my code if anyone can help me this I would be grateful
Map<String, String> signRequest(String param) {
var method = "POST";
var uri = endpoint;
var secretKey = secretKey;
var accessKey = accessKey;
var region = awsRegion;
var service = serviceType;
var host = baseUrl;
var date = DateFormat("yyyyMMdd'T'HHmmss'Z'").format(DateTime.now().toUtc());
var date2 = DateFormat("yyyyMMdd").format(DateTime.now().toUtc());
var requestBody = utf8.encode(json.encode(param.toLowerCase()));
var hashedPayloads = sha256.convert(requestBody).toString().toLowerCase();
var canonicalUri = uri;
var canonicalQuerystring = "";
var canonicalHeaders =
"content-type:application/json\nhost:$host\nx-amz-content-sha256:$hashedPayloads\nx-amz-date:$date\n";
var signedHeaders = "content-type;host;x-amz-content-sha256;x-amz-date";
var canonicalRequest =
"$method\n$canonicalUri\n$canonicalQuerystring\n$canonicalHeaders\n$signedHeaders\n$hashedPayloads";
var credentialScope = "$date2/$region/$service/aws4_request";
var stringToSign =
"${ApiConstants.hmacShaTypeString}\n$date\n$credentialScope\n${sha256.convert(utf8.encode(canonicalRequest))}";
var kSecret = "AWS4$secretKey";
var kDate = Hmac(sha256, utf8.encode(kSecret))
.convert(utf8.encode(date2))
.toString();
var kRegion = Hmac(sha256, utf8.encode(kDate))
.convert(utf8.encode(region))
.toString();
var kService = Hmac(sha256, utf8.encode(kRegion))
.convert(utf8.encode(service))
.toString();
var kSigning = Hmac(sha256, utf8.encode(kService))
.convert(utf8.encode("aws4_request"))
.toString();
var signature = Hmac(sha256, utf8.encode(kSigning))
.convert(utf8.encode(stringToSign))
.toString();
var authorizationHeader =
"${ApiConstants.hmacShaTypeString} Credential=$accessKey/$credentialScope, SignedHeaders=$signedHeaders, Signature=$signature";
Map<String, String> headers = {
"Content-Type": "application/json",
"X-Amz-Date": date,
"X-Amz-Content-Sha256": hashedPayloads,
"Authorization": authorizationHeader
};
return headers;
}
Status code: 403
Got this message in response:
{"message":"The request signature we calculated does not match the signature you provided. Check your AWS Secret Access Key and signing method. Consult the service documentation for details.\n\nThe Canonical String for this request should have been"}

Call AWS-SageMaker API in flutter

I'm trying to call a SageMaker API in flutter but the header has some issues related to Signature.
Map<String, String> signRequest(String param) {
var method = "POST";
var uri = endpoint;
var secretKey = secretKey;
var accessKey = accessKey;
var region = awsRegion;
var service = serviceType;
var host = baseUrl;
var date = DateFormat("yyyyMMdd'T'HHmmss'Z'").format(DateTime.now().toUtc());
var date2 = DateFormat("yyyyMMdd").format(DateTime.now().toUtc());
var requestBody = utf8.encode(json.encode(param.toLowerCase()));
var hashedPayloads = sha256.convert(requestBody).toString().toLowerCase();
var canonicalUri = uri;
var canonicalQuerystring = "";
var canonicalHeaders =
"content-type:application/json\nhost:$host\nx-amz-content-sha256:$hashedPayloads\nx-amz-date:$date\n";
var signedHeaders = "content-type;host;x-amz-content-sha256;x-amz-date";
var canonicalRequest =
"$method\n$canonicalUri\n$canonicalQuerystring\n$canonicalHeaders\n$signedHeaders\n$hashedPayloads";
var credentialScope = "$date2/$region/$service/aws4_request";
var stringToSign =
"${ApiConstants.hmacShaTypeString}\n$date\n$credentialScope\n${sha256.convert(utf8.encode(canonicalRequest))}";
var kSecret = "AWS4$secretKey";
var kDate = Hmac(sha256, utf8.encode(kSecret))
.convert(utf8.encode(date2))
.toString();
var kRegion = Hmac(sha256, utf8.encode(kDate))
.convert(utf8.encode(region))
.toString();
var kService = Hmac(sha256, utf8.encode(kRegion))
.convert(utf8.encode(service))
.toString();
var kSigning = Hmac(sha256, utf8.encode(kService))
.convert(utf8.encode("aws4_request"))
.toString();
var signature = Hmac(sha256, utf8.encode(kSigning))
.convert(utf8.encode(stringToSign))
.toString();
var authorizationHeader =
"${ApiConstants.hmacShaTypeString} Credential=$accessKey/$credentialScope, SignedHeaders=$signedHeaders, Signature=$signature";
Map<String, String> headers = {
"Content-Type": "application/json",
"X-Amz-Date": date,
"X-Amz-Content-Sha256": hashedPayloads,
"Authorization": authorizationHeader
};
return headers;
}
Status code: 403
Got this message in response:
{"message":"The request signature we calculated does not match the signature you provided. Check your AWS Secret Access Key and signing method. Consult the service documentation for details.\n\nThe Canonical String for this request should have been"}

Azure Search CreateIndexAsync fails with CamelCase field names FieldBuilder

Azure Search V11
I can't get this to work. But with the standard FieldBuilder the index is created.
private static async Task CreateIndexAsync(SearchIndexClient indexClient, string indexName, Type type)
{
var builder = new FieldBuilder
{
Serializer = new JsonObjectSerializer(new JsonSerializerOptions {PropertyNamingPolicy = new CamelCaseNamingPolicy()})
};
var searchFields = builder.Build(type).ToArray();
var definition = new SearchIndex(indexName, searchFields);
await indexClient.CreateIndexAsync(definition);
}
`
public class CamelCaseNamingPolicy : JsonNamingPolicy
{
public override string ConvertName(string name)
{
return char.ToLower(name[0]) + name.Substring(1);
}
}
See our sample for FieldBuilder. Basically, you must use a naming policy for both FieldBuilder and the SearchClient:
var clientOptions = new SearchClientOptions
{
Serializer = new JsonObjectSerializer(
new JsonSerializerOptions
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
}),
};
var builder = new FieldBuilder
{
Serializer = clientOptions.Serializer,
};
var index = new SearchIndex("name")
{
Fields = builder.Build(type),
};
var indexClient = new SearchIndexClient(uri, clientOptions);
await indexClient.CreateIndexAsync(index);
await Task.DelayAsync(5000); // can take a little while
var searchClient = new SearchClient(uri, clientOptions);
var response = await searchClient.SearchAsync("whatever");
While this sample works (our sample code comes from oft-executed tests), if you have further troubles, please be sure to post the exact exception message you are getting.

Get id of last Rest API POST using Entity Framework

I need to be able to access the id of a new Post. I will be using this id to populate another field called LocationId like this: "L" + id = LocationId (example L22) where 22 is the id of the new Post. Here is the code for my Post request:
private async void BtnSubmit_Clicked(object sender, EventArgs e)
{
var imageArray = FilesHelper.ReadFully(file.GetStream());
file.Dispose();
var location = new Models.Location()
{
LocationName = EntName.Text,
ImageArray = imageArray,
};
ApiServices apiServices = new ApiServices();
bool response = await apiServices.PostLocation(location);
bool response2 = await apiServices.InputLocationId(id, location);
if (!response || !response2)
{
await DisplayAlert("Alert", "Something wrong", "Cancel");
}
else
{
await DisplayAlert("Hi", "Your record has beed added successfully", "Alright");
}
await Navigation.PushAsync(new SetupPage());
This is on the client side. I have all the APIs created (such as PostLocation and InputLocationId)on Azure SQL Server. This is for a mobile inventory app built using Xamarin.
public async Task<bool> PostLocation(Location location)
{
var json = JsonConvert.SerializeObject(location);
var httpClient = new HttpClient();
var content = new StringContent(json, Encoding.UTF8, "application/json");
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("bearer", Settings.AccessToken);
var wimsApiUrl = "http://xxxxxxx.azurewebsites.net/api/Locations";
//Get the Body of the Post
var body = await httpClient.PostAsync(wimsApiUrl, content);
//Convert it to a string
var jString = await body.Content.ReadAsStringAsync();
//Place it in a JSON Object
JObject joResponse = JObject.Parse(jString);
//Parse the JSON Object into an Int from a String
var id = int.Parse(joResponse["Id"].ToString());
//This is used in my other script to Put the LocationId of Lxx
AddNewLocationPage.NewLocationId = id;
return body.IsSuccessStatusCode;
}
My Post Location API:
// POST: api/Locations
[ResponseType(typeof(Location))]
public IHttpActionResult PostLocation([FromBody] Location location)
{
string userId = User.Identity.GetUserId();
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
var stream = new MemoryStream(location.ImageArray);
var guid = Guid.NewGuid().ToString();
var file = String.Format("{0}.jpg", guid);
var folder = "~/Content/Images";
var fullPath = String.Format("{0}/{1}", folder, file);
var response = FilesHelper.UploadPhoto(stream, folder, file);
if (response)
{
location.ImagePath = fullPath;
}
var newLocation = new Location()
{
LocationName = location.LocationName,
User = userId,
ImagePath = location.ImagePath
};
db.Locations.Add(newLocation);
db.SaveChanges();
return Ok(new { newLocation.Id});
}
I will then take the id and put it in this Put Request to create the LocationId:
public async Task<bool> InputLocationId(int id, Location location)
{
var json = JsonConvert.SerializeObject(location);
var httpClient = new HttpClient();
var content = new StringContent(json, Encoding.UTF8, "application/json");
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("bearer", Settings.AccessToken);
var wimsApiUrl = "http://xxxxxxx.azurewebsites.net/api/Locations/InputLocationId/";
var completeUrl = String.Format("{0}{1}", wimsApiUrl, id);
var response = await httpClient.PutAsync(completeUrl, content);
return response.IsSuccessStatusCode;
}
The InputLocationId API will automatically create the LocationId. Here is my API:
// PUT: api/Locations/5
[HttpPut]
[ResponseType(typeof(void))]
[Route("api/Locations/InputLocationId/{id}")]
public IHttpActionResult InputLocationId(int id, [FromBody] Location location)
{
//string userId = User.Identity.GetUserId();
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
var result = db.Locations.FirstOrDefault(locationId => locationId.Id == id);
var resultant = String.Format("L{0}", id);
location.LocationName = location.LocationName;
result.LocationId = resultant;
db.SaveChanges();
return Ok("The record has been updated");
}
I am simply stuck on how to access that id!
// get the response body
var body = await httpClient.PostAsync(wimsApiUrl, content);
// load it into a JSON object using Newtonsoft
JObject data = JObject.Parse(body);
// get the id
var id = int.Parse(data["id"]);
The returns need to be converted into a string from the HttpResponseMessage.
var body = await httpClient.PostAsync(wimsApiUrl, content);
var jString = await body.Content.ReadAsStringAsync();
Then we can place it into a JSON Object:
JObject joResponse = JObject.Parse(jString);
Now this JSON Object can be parsed into an Int. Note it needs to be converted to a string.
var id = int.Parse(joResponse["Id"].ToString());

asp.net core 2.0 GitHub has with GetExternalLoginInfoAsync

I config service for GitHub
services.AddOAuth("GitHub", "Github", o =>
{
o.ClientId = Configuration["Authentication:GitHub:ClientId"];
o.ClientSecret = Configuration["Authentication:GitHub:ClientSecret"];
o.CallbackPath = new PathString("/signin-github");
o.AuthorizationEndpoint = "https://github.com/login/oauth/authorize";
o.TokenEndpoint = "https://github.com/login/oauth/access_token";
o.UserInformationEndpoint = "https://api.github.com/user";
o.ClaimsIssuer = "OAuth2-Github";
o.SaveTokens = true;
// Retrieving user information is unique to each provider.
o.ClaimActions.MapJsonKey(ClaimTypes.NameIdentifier, "id");
o.ClaimActions.MapJsonKey(ClaimTypes.Name, "login");
o.ClaimActions.MapJsonKey("urn:github:name", "name");
o.ClaimActions.MapJsonKey(ClaimTypes.Email, "email", ClaimValueTypes.Email);
o.ClaimActions.MapJsonKey("urn:github:url", "url");
o.Events = new OAuthEvents
{
OnCreatingTicket = async context =>
{
// Get the GitHub user
var request = new HttpRequestMessage(HttpMethod.Get, context.Options.UserInformationEndpoint);
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", context.AccessToken);
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var response = await context.Backchannel.SendAsync(request, context.HttpContext.RequestAborted);
response.EnsureSuccessStatusCode();
var user = JObject.Parse(await response.Content.ReadAsStringAsync());
context.RunClaimActions(user);
}
};
});
When I login on GitHub I redirect to action and in action has line ...
var info = await _signInManager.GetExternalLoginInfoAsync();//return null
That line always return null.
Can you help me?