Issues getting Amazon Alexa Address API to work - c#

Im having major dramas getting the Amazon Alexa address api to work in the C# Web Api app i have created using AlexaSkillsKit.Net
var apiEndpoint = context.System.ApiEndpoint;
var deviceId = context.System.Device.DeviceId;
var apiAccessToken = context.System.ApiAccessToken;
var url = string.Format("{0}/v1/devices/{1}/settings/address", apiEndpoint, deviceId);
var client = new HttpClient();
client.DefaultRequestHeaders.Clear();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", apiAccessToken);
client.DefaultRequestHeaders.Add("User-Agent", "Request-Promise");
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
string response = client.GetAsync(url).Result.Content.ReadAsStringAsync().Result;
The response i get back is as follows:
{"type":"FORBIDDEN","message":"The authentication token is not valid."}
Im at a loss as to why im getting this error
I have given my app permissions to get the Full Address

I have got this to work, i just needed to send the Permissions Card back to the user
https://developer.amazon.com/docs/custom-skills/device-address-api.html

Related

How to POST to a specific URL using the Microsoft Graph Client

I'm trying to send a POST request to the following URL using the MS Graph Client.
https://graph.microsoft.com/v1.0/sites/{SiteID}/lists/Documents/contentTypes/addCopyFromContentTypeHub
I looked at the various Request Builders and didn't see anything for "addCopyFromContentTypehub". There's a "ContentTypeAddCopyRequestBuilder", but that's a different action.
I tried getting access to the graph client's HttpProvider, but I can't figure out how to send the authentication with the request.
var requestUrl = graphServiceClient.Sites[siteId].Lists["Documents"].ContentTypes.AppendSegmentToRequestUrl("addCopyFromContentTypeHub");
var contentTypeId = "<ID>";
var body = $"{{\"contentTypeId\": \"{contentTypeId}\"}}";
using (var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, requestUrl))
{
httpRequestMessage.Content = new StringContent(requestUrl, Encoding.UTF8, "application/json");
//Errors here
var result = await graphServiceClient.HttpProvider.SendAsync(httpRequestMessage);
};
There error I get is:
"MsalUiRequiredException: No account or login hint was passed to the AcquireTokenSilent call."
My graph client uses an Azure AD App Registration to make all the calls so I need to include ".WithAppOnly()" on all my requests, but I don't see a way to do that using graphServiceClient.HttpProvider
Any help would be appreciated. Thanks!
You can authenticate HttpRequestMessage through Graph client
await graphServiceClient.AuthenticationProvider.AuthenticateRequestAsync(httpRequestMessage);
Code:
using (var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, requestUrl))
{
httpRequestMessage.Content = new StringContent(requestUrl, Encoding.UTF8, "application/json");
await graphServiceClient.AuthenticationProvider.AuthenticateRequestAsync(httpRequestMessage);
var result = await graphServiceClient.HttpProvider.SendAsync(httpRequestMessage);
};

Why getting 401 when trying validating Token

I have a Bearer token and need to validate it against a api and validateToken endpoint. The endpoint aspects a json like that:
{
"jwtToken": "my token"
}
At the swagger I try successful this endpoint using url
http://10.212.226.31:5022/api/v1/validateToken
But I need to validate from code and there I get a 401 'Unauthorized'.
HttpClient client = new HttpClient
{
BaseAddress = new Uri("http://10.212.226.31:5022/")
};
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
string token = accessToken.Replace("Bearer ", "");
HttpResponseMessage response = await client.PostAsJsonAsync(
"api/v1/validateToken", token);
At the response object I get the 401.
What is wrong? Some thing about the json?
How to hand over the right stuff to the endpoint?
Additions:
I work remote on a virtual machine from a costumer and he does not allow installing software. Fiddler and co is not available.
I tried also this, but it's not working:
ValidateTokenRequest tokenJson = new ValidateTokenRequest
{
jwtToken = token
};
HttpResponseMessage response = await client.PostAsJsonAsync(
"api/v1/validateToken", tokenJson);
I needed to authenticate my self at the endpoint, to add the token to the header.
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
Now it works. Thanks to everybody!

Send POST request from webapi c# to onesignal url

I'm very new on this and I need some help. I'm trying to send a notification from my webapi to my app. To do this a need just send a post to the url("https://onesignal.com/api/v1/notifications") with some informations (Header from authorization and content-type). But when I send the post it takes a long and and I just get The operation timeout has been reached, no message errors that could help me. I tryed the code from onesignal's documentation from asp.net solutions but isn't worked for me. Anyone can help? Or just help how can I trace the error with my requisiton? After try the code from onesignal's documentation I decided use the following code(both codes had the same behavior):
using (var client = new HttpClient())
{
var url = new Uri("https://onesignal.com/api/v1/notifications");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", "Rest ID");
var obj = new
{
app_id = "APP ID",
contents = new { en = "English Message" },
included_segments = new string[] { "All" }
};
var json = JsonConvert.SerializeObject(obj);
var content = new StringContent(json, Encoding.UTF8, "application/json");
var response = await client.PostAsync(url, content);
}
For some reason is taking a long time to send a notification and return some response for me. So I increase the timeout to wait the response and don't get a task cancelled. Hope help someone.

Https client with authorization in C#

I'm trying to create a https client in C#.
I had HTTP client which worked fine and I changed it to work with HTTPS. But unfortunately there is something wrong with the authorization (the server uses OAuth 2).
My program sends a request to a server and gets the token. But it can't get or send any data from the server.
The server works fine with other clients, so it's not its fault.
This is a piece of code which causes the problem. I know that, because when I comment authorization on the server, the data is send (everything is fine).
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(
"Basic", Convert.ToBase64String(System.Text.ASCIIEncoding.ASCII.GetBytes(
string.Format("Authorization: {0}", token))));
This is the whole function, which should send data:
WebRequestHandler handler = new WebRequestHandler();
X509Certificate certificate = GetMyX509Certificate();
handler.ClientCertificates.Add(certificate);
var client = new HttpClient(handler);
string uri = "https://192.168.0.10:8443/data";
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(
"Basic", Convert.ToBase64String(System.Text.ASCIIEncoding.ASCII.GetBytes(
string.Format("Authorization: {0}", token))));
client.BaseAddress = new Uri(uri);
var parameters = new Dictionary<string, string>();
parameters["name"] = name;
parameters["surname"] = surname;
JavaScriptSerializer serializer = new JavaScriptSerializer();
var json = serializer.Serialize(parameters);
System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
var response = client.PostAsync(uri, new StringContent(json, System.Text.Encoding.UTF8, "application/json")).Result;
Console.WriteLine((response.StatusCode.ToString()));
string resultContent = response.Content.ReadAsStringAsync().Result;
Console.WriteLine(resultContent);
I guess I'm missing something in the header but can't find any information in the documentation about that.
It's a difficult issue so any advice will be very appreciated.
You shouldn't be including the HTTP header name ("Authorization: ") in the parameter of the AuthenticationHeaderValue. Setting the Authorization property will add the header to the request.
Additionally for OAuth 2, you probably want to be using "Bearer" as the scheme and not encoding token with base64.
Something like this should therefore work:
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);

Sending Autherization crud authorization

I am writing (Attempting to write a crud application!)
I need to send a Key to the server before I can start using the service.
this.InitializeComponent();
client = new HttpClient();
client.BaseAddress = new Uri("http://dignity-network.org/api/");
I have tried
client.BaseAddress = new Uri("NO3ID81WJECJXZI83A3YYPGJKJLNEJMQ#dignity-network.org/api/")
But this does not work, what is the correct request to send authorization to a server ?
Thanks.
All depends how the server accepts and implements authorization code.
if you have to send the auth code before you start to use , you just need:
HttpContent content = HttpContent.Create(yourAuthCode, Encoding.UTF8);
HttpResponseMessage response = client.Post(new Uri ("http://dignity-network.org/api/"), content);

Categories

Resources