Hello everyone my name is Taniguchi.
I've tried retrieving an entity from Dynamics 365 Finance and Operations and i did it on postman but now i having difficulties in asp.net core I was able to get the token but when i try to retrieve the entity the response gives me a html and this html leads me to the Dynamics 365 Finance and Operations Page.
My code:
`
var httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
const string environmentsUri = "https://trial-0z4qfj.sandbox.operations.dynamics.com/data/PartyContacts";
var response = httpClient.GetAsync(environmentsUri).Result;
var content = response.Content.ReadAsStringAsync().Result;
what am i doing wrong ? do i need to authenticate again ?
I suspect the Token you receive is not correct/complete.
I remember I faced the similar issue, I would request you to follow this blog post and try to receive Token as shown This shall help you solve your issue.
In addition I would recommend you use Organizaiton service with Webapi/Access Token. It will give you native library usage and you could query crm easily.
Try this blog for Orgservice
Seems like you are only using the parameter accessToken instead of the variable value. Depends on how you declared accessToken ofc. The rest seems fine.
Try:
httpClient.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("Bearer", token.accessToken);
Related
I have registered an app in Azure. I can get access_token from oauth2/v2.0/token from password grant. I can also get refresh_token from oauth2/v2.0/token using refresh_token grant
But, How do I request a resource in Microsoft Azure using an access_token?
In short how can we use the generated access_token in azure?
When you would request anything on azure you have to pass your access
token as your request headerrequest.Headers.Authorization which is
Bearer token.
Here I am giving you an example how you could access azure resource using your access token.
//New Block For Accessing Data from Microsoft Graph Rest API
HttpClient _client = new HttpClient();
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, string.Format("https://graph.microsoft.com/v1.0/users"));
//Passing Token For this Request
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", "Pass Your Token Here");
HttpResponseMessage response = await _client.SendAsync(request);
//Get User List From Response
dynamic objGpraphUserList = JsonConvert.DeserializeObject<dynamic>(await response.Content.ReadAsStringAsync());
I am accessing Azure Active Directory User List using access token. I got this response
See the screenshot below:
Azure Resource API Access Sample :
As Per Gaurav Mantri's Recommendation I am also giving you another example how you could get azure resource group information. See below code snippet
//How You Would Request Microsft Resource Management API For Resources List
var azureSubcriptionId = "Your_Azure_Subcription_Id";
var resourceGroupName = "Your_Resource_Group_Name";
HttpClient _client = new HttpClient();
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, string.Format("https://management.azure.com/subscriptions/{0}/resourceGroups/{1}/resources?api-version=2019-10-01", azureSubcriptionId, resourceGroupName));
//Passing Token For this Request
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", "Pass Your Token Here");
HttpResponseMessage response = await _client.SendAsync(request);
//Get User List From Response
dynamic objAzureResourceGroupList = JsonConvert.DeserializeObject<dynamic>(await response.Content.ReadAsStringAsync());
Also Tested on PostMan.
For more details you could refer Official Docs
Hope this would help you.
This process has been defined very clearly here: https://learn.microsoft.com/en-us/rest/api/azure. Especially look at the section titled Create the request which will tell you exactly what needs to be done.
I have my telegram application with app's api_id and app's api_hash.
I used TLSharp library for implementing my own things. But now I need to use this https://core.telegram.org/method/auth.checkPhone telegram api method, but it's not implemented in TLSharp library!
I don't mind doing it all manually, but I don't know how!
I know how you send post requests in C#, example:
var response = await client.PostAsync("http://www.example.com/index", content);
but in this specific case I don't. Because I don't know:
1) what link should I use for sending post requests? I couldn't find it on the telegram's website.
2) what content should I pass there? Should it be just "(auth.checkPhone "+380666454343")" or maybe the whole "(auth.checkPhone "+380666454343")=(auth.checkedPhonephone_registered:(boolFalse)phone_invited:(boolFalse))" ?
So, How do I sent this post request to the telegram api? (NOT telegram bot api!)
Try to use System.Net.Http like in this example (auth request to the server):
var user = new { login = "your login", password = "your pass" };
string json = JsonConvert.SerializeObject(user);
HttpContent content = new StringContent(json, Encoding.UTF8, "application/json");
HttpClient client = new HttpClient();
HttpRequestMessage request = new HttpRequestMessage();
request.RequestUri = new Uri("server route link"); // can be like https://a100.technovik.ru:1000/api/auth/authenticate
request.Method = HttpMethod.Post;
request.Content = content;
HttpResponseMessage response = await client.SendAsync(request);
responseText.Text = await response.Content.ReadAsStringAsync();
I think based on a brief look, that it would be more along the lines of your second example, e.g.:
var phonenumber = "0123456789";
var content =
$#"(auth.checkPhone ""{phonenumber}"")"+
"=(auth.checkedPhone phone_registered: (boolFalse) phone_invited:(boolFalse))";
var result = DoHttpPost("http://some.example.com/api/etc", content);
(note: I've not listed the actual mechanics of an HTTP Request here, as that is covered in plenty of detail elsewhere - not least in the other current answer supplied to you; DoHttpPost() is not a real method and exists here only as a placeholder for this process)
And since the payload of this appears to indicate the exact function and parameters required, that you'd just send it to the base api endpoint you use for everything, but I can't say for sure...
I do note they do appear to have links to source code for various apps on the site though, so perhaps you'd be better off looking there?
UPDATE: Figured this out. I DID need to add the authorization header as answered below but I also believe the issue for my particular use case is that the access token (which I verified through Postman) required more scopes to authenticate me fully, which makes sense since this API contains surveys that I am trying to access, which are also linked to a Google account. Once I added the extra scopes needed to access the surveys to the token request along with the authorization header code below I was able to connect successfully.
More info on adding scopes to C# code can be found here: http://www.oauthforaspnet.com/providers/google/
Hope this helps anyone running into similar issues. Thanks all!
I am trying to make a GET call to a Google API but it keeps responding with "Unauthorized" while I am logged in to Gmail. I've already implemented Google+ Sign-In in StartUp.Auth.cs and even saved the access token for later use.
So how do I get the HttpClient to authorize me?
I have an access token available but I do not know how to pass it in properly. I've seen examples with usernames and passwords, but I should not need to pass those parameters if I already have an access token? If anything, I should be able to have the user redirected to a login page instead if needed when I log out before running the solution.
What I am expecting when the project is run, is the result of the GET call to come back in the form of json but it always says I'm "Unauthorized" and I am probably missing 1 line of code somewhere...
Here is the code I am using:
using (HttpClient client = new HttpClient())
{
string _url = "https://www.googleapis.com/consumersurveys/v2/surveys?key={MY_API_KEY}";
client.BaseAddress = new Uri(_url);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
using (HttpResponseMessage response = client.GetAsync(_url).Result)
{
if (response.IsSuccessStatusCode)
{
using (HttpContent content = response.Content)
{
var Content = content.ReadAsStringAsync();
ViewBag.GoogleResponse = Content.ToString();
}
}
else
{
// THIS IS ALWAYS UNAUTHORIZED!
ViewBag.GoogleResponse = response.StatusCode + " - " + response.ReasonPhrase;
}
}
}
Please help with ideas or suggestions. Thanks!
You need to pass the auth token in an Authorization Header:
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
Have you ever gotten an response for this api/survey? If you were unable to get a response from the API by hitting it with Postman, you may have issues in the way you are targeting the API. The error being returned there seems like you weren't including the token in your request header. Did you click the Authorization tab below the request URL to add the OAuth token to your header? (Keep in mind that the {} characters need to be URL encoded)
Also, when you are referencing MY_API_KEY, is that analagous to your surveyId?
I don't have a lot of experience here, but I have a couple of suggestions :
1) I agree with Pedro, you definitely need to include the Authorization Header in your request.
2) If your MY_API_KEY is in fact the survey ID, you may be providing an incorrect URL (GoogleAPIs documentation indicates that it should be < http://www.googleapis.com/consumer-surveys/v2/surveys/surveyId >
Recommendation (after moving your API key to a string var named MY_API_KEY) :
string _url = "https://www.googleapis.com/consumersurveys/v2/surveys/";
client.BaseAddress = new Uri(_url);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", ViewBag.GoogleAccessToken);
using (HttpResponseMessage response = client.GetAsync(MY_API_KEY).Result)
{
if (response.IsSuccessStatusCode)
{
using (HttpContent content = response.Content)
{
var Content = content.ReadAsStringAsync();
ViewBag.GoogleResponse = Content.ToString();
}
}
Reference:
https://developers.google.com/consumer-surveys/v2/reference/
http://www.asp.net/web-api/overview/advanced/calling-a-web-api-from-a-net-client
I'm using Trello's Developer API's implementation of OAuth to post stuff to a list.
I've successfully made a request and got my oauth_token and oauth_token_secret back from https://trello.com/1/OAuthGetRequestToken
But when I call https://trello.com/1/OAuthAuthorizeToken, passing the oauth_token that I've just received, I get a response of 'App not found'.
Can anyone help?
EDIT: Here's what I'm getting back from https://trello.com/1/OAuthGetRequestToken
oauth_token=8d0e43fd0cc67726567d49ae5e818852&oauth_token_secret=[secret]
And here's the Authorization header I'm sending (escaped in C#)
"OAuth oauth_version=\"1.0\", oauth_signature_method=\"HMAC-SHA1\", oauth_nonce=\"8335006\", oauth_timestamp=\"1414663625\", oauth_consumer_key=\"9612eaca23c7bdd3eca60dc8c2a8159c\", oauth_signature=\"M6sLyyfHGYXOtQnLJexDx96kbFo=\", oauth_token=\"8d0e43fd0cc67726567d49ae5e818852\""
Am I doing something wrong or is this an error on Trello's end?
EDIT: I'm using RestSharp to call the Trello API, as below:
var client = new RestSharp.RestClient("https://trello.com/");
var request = new RestSharp.RestRequest("1/OAuthAuthorizeToken", Method.GET);
EDIT: Here's the complete RestSharp code:
var client = new RestSharp.RestClient("https://trello.com/");
var request = new RestSharp.RestRequest("1/OAuthAuthorizeToken", Method.GET);
Uri uri = new Uri(string.Format("{0}/{1}", client.BaseUrl, request.Resource));
string authHeader = GenerateAuthorizationHeader(uri);
//This is the output of GenerateAuthorizationHeader()
//string authHeader = "OAuth oauth_version=\"1.0\", oauth_signature_method=\"HMAC-SHA1\", oauth_nonce=\"8335006\", oauth_timestamp=\"1414663625\", oauth_consumer_key=\"9612eaca23c7bdd3eca60dc8c2a8159c\", oauth_signature=\"M6sLyyfHGYXOtQnLJexDx96kbFo=\", oauth_token=\"8d0e43fd0cc67726567d49ae5e818852\"";
request.AddHeader("Authorization", authHeader);
The GenerateAuthorizationHeader method uses OAuth.OAuthBase to generate the TimeStamp and Signature for the OAuth request.
Looks like it might be a trello problem...
this user, had the wrong key by the sounds of things.
are you 100% sure that the key is correct.
Getting "App not found" from Trello Authentication
I had the same problem, the thing here is that OAuth is version 1.0
When you get the token and token secret from the first call you have to make your user to visit https://trello.com/1/OAuthAuthorizeToken not you.
In your case you have to redirect your user to https://trello.com/1/OAuthAuthorizeToken?oauth_token=8d0e43fd0cc67726567d49ae5e818852&scope=read,write,account
He will get a page where he can Allow the access. Then you will get a verification code in the page after the authorization to continue with your process (GetAccessToken).
You can try this as a test, in a real application you have to specify a callback url and an application name in the OAuthAuthorizeToken call.
After Twitter deprecated their Twitter API 1.0, I've tried several methods in order to get the 1.1 API working for my Windows 8 application. However, what you see below is basically what I've ended up with:
public List<UserTweet.User> jsonFromTwitter;
private async void fetchTweet()
{
var jsonTwitter = new Uri("http://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=stackoverflow&result_type=recent");
HttpClient client = new HttpClient();
var request = new HttpRequestMessage(HttpMethod.Get, jsonTwitter);
var oAuthHeader = "OAuth oauth_consumer_key=\"XXXXX\", oauth_nonce=\"XXXXX\", oauth_signature=\"XXXXX\", oauth_signature_method=\"HMAC-SHA1\", oauth_timestamp=\"1318622958\", oauth_token=\"XXXXX-XXXXXX\", oauth_version=\"1.0\"";
request.Headers.Add("Authorization", oAuthHeader);
var response = await client.SendAsync(request);
var responseString = await response.Content.ReadAsStringAsync();
jsonFromTwitter = JsonConvert.DeserializeObject<List<UserTweet.User>>(await client.GetStringAsync(responseString));
//listbox.ItemsSource = jsonFromTwitter;
}
However, this won't do much good, and it switches between mainly a couple of errors. One of them can be seen below, and the other one is "Could not authenticate user" or similar, basically there's something wrong with the headers as far as I've understood.
Anyone got any ideas on how to construct a working OAuth header for this? I'm clueless at the moment.
There's a lot more you need to do for the value assigned to the Authorization header - plain text won't work. The following pages in the Twitter OAuth documentation might help you get started in the right direction.
Twitter's Docs have a section on Authentication
Authorizing a Request
Creating Signatures