Api GetAccessToken in C# not return - c#

I used the following code to get a token value but error (The remote certificate is invalid according to the validation procedure.) returns Thanks for the guidance.
private static async Task<string> GetAccessToken()
{
using (var client = new HttpClient())
{
const string URL = "https://bime.net.iraneit.com:3023/BimeApiManager_Main/api/EITAuthentication/GetAppToken";
client.BaseAddress = new Uri(URL);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
ICollection<KeyValuePair<String, String>> postData = new Dictionary<String, String>();
postData.Add(new KeyValuePair<String, String>("appname", " "));
postData.Add(new KeyValuePair<String, String>("secret", " "));
FormUrlEncodedContent content = new FormUrlEncodedContent(postData);
var ttt = content;
var result = await client.PostAsync(URL, content);
var response = await client.PostAsync("appToken", content);
if (response.IsSuccessStatusCode)
{
string JString = await response.Content.ReadAsStringAsync();
object responseData = JsonConvert.DeserializeObject(JString);
return ((dynamic)responseData).access_token;
}
else
{
return null;
}
}
}

Related

C# calling aspnet webapi token endpoint works perfectly on my localhost but givens error on server

public static async Task<Tuple<bool, string>> GetTokenForAccess(this User user)
{
var scheme = HttpContext.Current.Request.IsSecureConnection ? "https://" : "http://";
string baseAddress = $"{scheme}{HttpContext.Current.Request.Url.Authority}";
using (var client = new HttpClient())
{
var accept = "application/json";
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Add("Accept", "*/*");
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded"));
string grant_type = "password";
string body = $"grant_type={grant_type}&username={user.PhoneNumber}&password={user.Password}&grant_access=true";
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, $"{baseAddress}/token")
{
Content = new StringContent(body,
Encoding.UTF8,
"application/x-www-form-urlencoded")
};
var response = await client.SendAsync(request);
var token = response.Content.ReadAsAsync<Token>(new[] { new JsonMediaTypeFormatter() }).Result;
if (string.IsNullOrEmpty(token.Error))
{
return new Tuple<bool, string>(true, token.AccessToken);
}
else
{
return new Tuple<bool, string>(false, token.Error);
}
}
}
You problem should be here:
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded"));
Remove the "application/json" because the default implementation of OAuthAuthorizationServerHandler only accepts form encoding (i.e. application/x-www-form-urlencoded) and not JSON encoding (application/JSON).

x-www-form-urlencoded in Xamarin

I'm working on Xamarin.Android App. I have to consume rest API of content type x-www-form-urlencoded. I'm unable to call the Rest API Successfully, before this, I consumed many web services but I'm working on this type of API first time. I'm stuck in this.
I tried two ways to consume it:
public static string makePostEncodedRequest(string url, string jsonparams)
{
string ret = "";
var httpwebrequest = (HttpWebRequest)WebRequest.Create(url);
httpwebrequest.ContentType = "application/x-www-form-urlencoded";
//httpwebrequest.Accept = Config.JsonHeaderAJ;
httpwebrequest.Method = Methods.Post.ToString();
byte[] bytearray = Encoding.UTF8.GetBytes(jsonparams);
using (var streamWriter = new StreamWriter(httpwebrequest.GetRequestStream(), Encoding.ASCII))
{
streamWriter.Write(bytearray);
streamWriter.Flush();
streamWriter.Close();
}
var httpResponse = (HttpWebResponse)httpwebrequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
ret = streamReader.ReadToEnd();
}
return ret;
}
the next one is:
Dictionary<string, string> requestParams = new Dictionary<string, string ();
requestParams.Add("value=", data1);
requestParams.Add("&value=", data2);
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded"));
HttpResponseMessage response = client.PostAsync(Config.DomainURl + Config.StudentLoginUrl, new FormUrlEncodedContent(requestParams)).Result;
var tokne = response.Content.ReadAsStringAsync().Result;
}
i have used the following code for authenticating user in my project might help you.
public static async Task<UserData> GetUserAuth(UserAuth userauth)
{
bool asd= CheckNetWorkStatus().Result;
if (asd)
{
var client = new HttpClient(new NativeMessageHandler());
client.BaseAddress = new Uri(UrlAdd);// ("http://192.168.101.119:8475/");
var postData = new List<KeyValuePair<string, string>>();
var dto = new UserAuth { grant_type = userauth.grant_type, password = userauth.password, username = userauth.username };
var nvc = new List<KeyValuePair<string, string>>();
nvc.Add(new KeyValuePair<string, string>("grant_type", userauth.grant_type));
nvc.Add(new KeyValuePair<string, string>("password", userauth.password));
nvc.Add(new KeyValuePair<string, string>("username", userauth.username));
var req = new HttpRequestMessage(HttpMethod.Post, UrlAdd + "token") { Content = new FormUrlEncodedContent(nvc) };
var res = await client.SendAsync(req);
if (res.IsSuccessStatusCode)
{
string result = await res.Content.ReadAsStringAsync();
var userData = JsonConvert.DeserializeObject<UserData>(result);
userData.ErrorMessage = "true";
return userData;
}
else
{
UserData ud = new UserData();
ud.ErrorMessage = "Incorrect Password";
return ud;
}
}
else
{
UserData ud = new UserData();
ud.ErrorMessage = "Check Ur Connectivity";
return ud;
}
}

200 status using refresh token

public async Task NewMethodAsync()
{
try
{
HttpClient objClient = new HttpClient();
Uri requestUri = new Uri("https://approvalbotbeta.azurewebsites.net/api/token");
Dictionary<string, string> pairs = new Dictionary<string, string>();
var client_ID = "<CLIENT ID>";
var client_secret = "<SECRET KEY STRING>";
pairs.Add("grant_type", "client_credentials");
pairs.Add("reply_url", "http://localhost");
FormUrlEncodedContent httpContent = new FormUrlEncodedContent(pairs);
var encordedString = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(client_ID + ":" + client_secret));
objClient.DefaultRequestHeaders.Add("Authorization", "Basic " + encordedString);
HttpResponseMessage respon = await objClient.PostAsync("https://approvalbotbeta.azurewebsites.net/api/token", httpContent);
if (respon.IsSuccessStatusCode)
{
Console.WriteLine(respon.Content.ReadAsStringAsync().Result);
var ww = respon.Content.ReadAsStringAsync().Result;
var response = JsonConvert.DeserializeObject<Response>(ww);
Console.WriteLine(response.access_token);
var acc_tkn = response.access_token;
// Uri requesturi = new Uri("https://approvalbotbeta.azurewebsites.net/api/send");
// Dictionary<string, string> pairs2 = new Dictionary<string, string>();
// pairs2.Add("Content-Type", "application/json");
// FormUrlEncodedContent httpContent2 = new FormUrlEncodedContent(pairs2);
// objClient.DefaultRequestHeaders.Add("Authorization", "Bearer",+ acc_tkn);
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
I coded this for getting access token, and got it. Now I want to get 200 status using this token and my URL. So what are the coding lines?
respon.StatusCode will get you 200.
If you mean that using this token you want to retrieve data from your API, use this:
using (var client = new HttpClient())
{
var url = "https://approvalbotbeta.azurewebsites.net/api/GetSomething";
client.DefaultRequestHeaders.Add("Authorization", "Bearer " + acc_tkn);
var response = await client.GetStringAsync(url);
// Parse JSON/XML response.
}
GetSomething is the method you want to call.
acc_tkn you got in your posted code.

httpclient header + content joined PostAsyn

I am trying to make a PostAsync request with c#. The following is my code.
static void Main(string[] args)
{
CookieContainer cookies = new CookieContainer();
HttpClientHandler handler = new HttpClientHandler();
handler.CookieContainer = cookies;
using (var client = new HttpClient(handler))
{
using (HttpResponseMessage getResponse = client.GetAsync("http://google.com").Result)
{
CheckStatusCode(getResponse);
String header = getResponse.Headers.ToString();
var content = CreateCollection(getResponse.Content);
var _stringHeaderContent = header + "\r" + content;
HttpContent _content = new StringContent(_stringHeaderContent, Encoding.UTF8);
Console.WriteLine(_content);
using (HttpResponseMessage postResponse = client.PostAsync("http://google.com",_content).Result)
{
Console.WriteLine(postResponse.Headers);
CheckStatusCode(postResponse);
Console.WriteLine(postResponse.Headers);
}
}
}
}
methods:
public static void CheckStatusCode(HttpResponseMessage response)
{
if (response.StatusCode != HttpStatusCode.OK)
throw new Exception(String.Format(
"Server error (HTTP {0}: {1}).",
response.StatusCode,
response.ReasonPhrase));
else
Console.WriteLine("200");
}
public static String CreateCollection(HttpContent content)
{
var myContent = content.ReadAsStringAsync().Result;
HtmlNode.ElementsFlags.Remove("form");
string html = myContent;
var doc = new HtmlAgilityPack.HtmlDocument();
doc.LoadHtml(html);
var input = doc.DocumentNode.SelectSingleNode("//*[#name='__Token']");
var token = input.Attributes["value"].Value;
//add all necessary component to collection
NameValueCollection collection = new NameValueCollection();
collection.Add("__Token", token);
collection.Add("returnURL", "");
collection.Add("Email", "11111111#hotmail.com");
collection.Add("Password", "1234");
String queryString = GenerateQueryString(collection);
return queryString;
}
public static string GenerateQueryString(NameValueCollection collection)
{
var array = (from key in collection.AllKeys
from value in collection.GetValues(key)
select string.Format("{0}={1}", WebUtility.UrlEncode(key), WebUtility.UrlEncode(value))).ToArray();
return string.Join("&", array);
}
The problem I am having with this code is nothing gets stored in _content. I am trying to make a postAsync request with the header and a part of the content joined. however when I make the postAsync request nothing is stored in _content. Therefore the request fails.
Can anyone explain to me how I can make a postAsync request with _stringHeaderContent?
Regards
This is the way how to use PostAsync:
...
var httpClient = new HttpClient();
var postData = new List<KeyValuePair<string, string>>();
postData.Add(new KeyValuePair<string, string>("a", "1"));
postData.Add(new KeyValuePair<string, string>("b", "2"));
var content = new FormUrlEncodedContent(postData);
var result = httpClient.PostAsync("http://127.0.0.1/a.php", content).Result;
...

Using a token to search on Twitter with OAuth2

Before Twitter switched to OAuth2, I was using the following query:
string atomTweetSearchURL = string.Format("http://search.twitter.com/search.atom?q={0}", searchText);
This no longer works, so now I'm trying to switch to OAuth2. I manage to successfully retrieve a token, but once I've got this, I seem to be unable to actually perform the search. Here's the latest incarnation of what I've tried:
var searchUrl = string.Format("https://api.twitter.com/1.1/search/tweets.json?q={0}&access_token={1}&token_type={2}", srchStr, twitAuthResponse.access_token, twitAuthResponse.token_type);
WebRequest srchRequest = WebRequest.Create(searchUrl);
using (var response2 = await srchRequest.GetResponseAsync())
{
Stream stream = response2.GetResponseStream();
using (StreamReader sr = new StreamReader(stream))
{
string jsonResponse = await sr.ReadToEndAsync();
}
}
This gives me a 400 - bad request.
I've also tried building the request like this:
System.Net.Http.HttpClient srchRequest = new System.Net.Http.HttpClient();
string authHdr = string.Format(srchHeaderFormat, twitAuthResponse.token_type, twitAuthResponse.access_token);
srchRequest.DefaultRequestHeaders.Add("Authorization", authHdr);
There's a massive quantity of articles out there detailing how to do this, but none of them seem to work correctly with WinRT. Can anyone point me in the right direction?
EDIT
Here's my code to get the token:
var oAuthConsumerKey = key;
var oAuthConsumerSecret = secret;
var oAuthUri = new Uri("https://api.twitter.com/oauth2/token");
var authHeaderFormat = "Basic {0}";
var authHeader = string.Format(authHeaderFormat,
Convert.ToBase64String(Encoding.UTF8.GetBytes(Uri.EscapeDataString(oAuthConsumerKey)
+ ":" +
Uri.EscapeDataString((oAuthConsumerSecret)))
));
var req = new HttpClient();
req.DefaultRequestHeaders.Add("Authorization", authHeader);
HttpRequestMessage msg = new HttpRequestMessage(new HttpMethod("POST"), oAuthUri);
msg.Content = new HttpStringContent("grant_type=client_credentials");
msg.Content.Headers.ContentType = new Windows.Web.Http.Headers.HttpMediaTypeHeaderValue("application/x-www-form-urlencoded");
HttpResponseMessage response = await req.SendRequestAsync(msg);
TwitAuthenticateResponse twitAuthResponse;
using (response)
{
string objectText = await response.Content.ReadAsStringAsync();
twitAuthResponse = JSonSerialiserHelper.Deserialize<TwitAuthenticateResponse>(objectText);
}
With the 1.1 API you don't pass the access token as part of the url, you need to include it as the Authorization header as "Bearer access_token" so you were almost there!
EDIT
To do this in the Windows.Web.Http namespace the following works:
private static async Task SearchTweets(AuthenticationResponse twitAuthResponse)
{
string srchStr = "tweet";
var client = new HttpClient();
var searchUrl = string.Format("https://api.twitter.com/1.1/search/tweets.json?q={0}", srchStr);
var uri = new Uri(searchUrl);
client.DefaultRequestHeaders.Authorization = new HttpCredentialsHeaderValue("Bearer", twitAuthResponse.AccessToken);
var response2 = await client.GetAsync(uri);
string content = await response2.Content.ReadAsStringAsync();
}
Or with System.Net.Http use the following:
This code will run the search for srchStr using the access token you already acquired as you showed in the first example:
var client = new HttpClient();
var searchUrl = string.Format("https://api.twitter.com/1.1/search/tweets.json?q={0}", srchStr);
var uri = new Uri(searchUrl);
client.DefaultRequestHeaders.Add("Authorization", string.Format("Bearer {0}", twitAuthResponse.access_token));
HttpResponseMessage response = await client.GetAsync(uri);
Task<string> content = response.Content.ReadAsStringAsync();
EDIT
This is a strange one, I tested your code and you're right it does throw an exception when attempting to add the Auth header, however the code I had used for grabbing the Access Token is almost identical but uses the System.Net.Http methods rather than the Windows.Web.Http ones that you use and it works, so I'll provide my code here, maybe this is a bug in the framework, or someone else can provide some more insight! This also uses the JSON.NET library which can be found on NuGet.
private static async Task SearchTweets(AuthenticationResponse twitAuthResponse)
{
string srchStr = "tweet";
var client = new HttpClient();
var searchUrl = string.Format("https://api.twitter.com/1.1/search/tweets.json?q={0}", srchStr);
var uri = new Uri(searchUrl);
client.DefaultRequestHeaders.Add("Authorization", string.Format("Bearer {0}", twitAuthResponse.AccessToken));
HttpResponseMessage response2 = await client.GetAsync(uri);
string content = await response2.Content.ReadAsStringAsync();
}
private async void GetAuthenticationToken()
{
var client = new HttpClient();
var uri = new Uri("https://api.twitter.com/oauth2/token");
var encodedConsumerKey = WebUtility.UrlEncode(TwitterConsumerKey);
var encodedConsumerSecret = WebUtility.UrlEncode(TwitterConsumerSecret);
var combinedKeys = String.Format("{0}:{1}", encodedConsumerKey, encodedConsumerSecret);
var utfBytes = System.Text.Encoding.UTF8.GetBytes(combinedKeys);
var encodedString = Convert.ToBase64String(utfBytes);
client.DefaultRequestHeaders.Add("Authorization", string.Format("Basic {0}", encodedString));
var data = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("grant_type", "client_credentials")
};
var postData = new FormUrlEncodedContent(data);
var response = await client.PostAsync(uri, postData);
AuthenticationResponse authenticationResponse;
using (response)
{
if (response.StatusCode != System.Net.HttpStatusCode.OK)
throw new Exception("Did not work!");
var content = await response.Content.ReadAsStringAsync();
authenticationResponse = JsonConvert.DeserializeObject<AuthenticationResponse>(content);
if (authenticationResponse.TokenType != "bearer")
throw new Exception("wrong result type");
}
await SearchTweets(authenticationResponse);
}
}
class AuthenticationResponse
{
[JsonProperty("token_type")]
public string TokenType { get; set; }
[JsonProperty("access_token")]
public string AccessToken { get; set; }
}

Categories

Resources