I'm trying to consume a WSDL web service and it requires an access token to be sent in the header. However, I keep getting a 401 error and I'm not sure if I am injecting the token correctly.
Heres a snippet of the code:
var client = new WsldClient();
var operationContext = new OperationContext(client.InnerChannel);
using (new OperationContextScope(operationContext))
{
var httpRequestProperty = new HttpRequestMessageProperty();
httpRequestProperty.Headers[HttpRequestHeader.Authorization] = "Bearer " + accessToken
operationContext.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = httpRequestProperty;
client.SomeMethod();
}
This returns a 401 error.
You can try the following code:
var client = new MyClient();
client.ClientCredentials.UserName.UserName = "username";
client.ClientCredentials.UserName.Password = "password";
var httpRequestProperty = new HttpRequestMessageProperty();
httpRequestProperty.Headers[HttpRequestHeader.Authorization] = "Basic " + Convert.ToBase64String(Encoding.ASCII.GetBytes(client.ClientCredentials.UserName.UserName + ":" + client.ClientCredentials.UserName.Password));
var context = new OperationContext(ormClient.InnerChannel);
using (new OperationContextScope(context))
{
context.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = httpRequestProperty;
return await client.SomeMethod();
}
Authorization Header is missing in Http request using WCF
http://plainoldstan.blogspot.com/2008/07/avoid-http-401-roundtrip-with-adding.html
Related
I have 2 projects one Web API that have a simple /Token api that returns a token for the logged in user
and the second project is .NET Core that will use the URL/Token method in the login form.
Here is the code on the method that is used to login in the second project
public async Task<IActionResult> OnPostAsync(string returnUrl = null)
{
var requestBody = new { grant_type = "password", username = Input.Email, password = Input.Password };
var data = Newtonsoft.Json.JsonConvert.SerializeObject(requestBody);
using (var client = new HttpClient())
using (var req = new HttpRequestMessage(HttpMethod.Get, "http://localhost:49470/Token"))
{
req.Content = new StringContent("{\"grant_type\":\"password\",\"username\":" + Input.Email + ",\"password\":" + Input.Password + "}", Encoding.UTF8, "application/json");
using (var rep = await client.SendAsync(req))
{
rep.EnsureSuccessStatusCode();
var content = await rep.Content.ReadAsStringAsync();
}
}
}
}
Error i'm facing:
The problem that i'm facing i always get a 400 (Bad Request) Error, ps: i'm new in .netcore
I've solved it, the problem was the api\Token body didn't accept the structure of the json parsed string
Simply i've used
var response = client.PostAsync("http://localhost:49470/Token", new StringContent("grant_type=password&username=" + Input.Email + "&password=" + Input.Password, Encoding.UTF8, "application/json")).Result;
I am trying to do this curl call to the new yahoo weather api with OAuth 1 like so:
[HttpGet]
public HttpResponseMessage getWeather()
{
using (HttpClient httpClient = new HttpClient())
{
httpClient.BaseAddress = new Uri("http://weather-ydn-yql.media.yahoo.com/");
httpClient.DefaultRequestHeaders.Accept.Clear();
httpClient.DefaultRequestHeaders.Add("Authorization", "OAuth oauth_consumer_key = \"(MY CONSUMER KEY)\", oauth_signature_method = \"HMAC-SHA1\", oauth_timestamp = \"1547473450\", oauth_nonce = \"Ll7ArdU1yN0\", oauth_version = \"1.0\", oauth_signature = \"(MY GENERATED SIGNATURE FROM POSTMAN)\"");
//httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("OAuth", "oauth_consumer_key = \"(MY CONSUMER KEY)\", oauth_signature_method = \"HMAC-SHA1\", oauth_timestamp = \"1547472939\", oauth_nonce = \"vu3HE92s6A3\", oauth_version = \"1.0\", oauth_signature = \"(MY GENERATED SIGNATURE FROM POSTMAN)\"");
HttpResponseMessage response = httpClient.GetAsync("forecastrss?location=hamilton&format=json").Result;
return response;
}
}
But when I run this it returns this error:
Please provide valid credentials. OAuth
oauth_problem="OST_OAUTH_PARAMETER_ABSENT_ERROR",
realm="yahooapis.com"
So it appears that my OAuth parameters are missing. My Question is how do I do a curl in ASP.NET C# with OAuth 1 authentication?
Figured it out using RestClient
var client = new RestClient("http://weather-ydn-yql.media.yahoo.com/forecastrss?location=hamilton&format=xml");
var request = new RestRequest(Method.GET);
request.AddHeader("Postman-Token", "ac0c256b-e727-4b01-b4fe-edd8b7d7073a");
request.AddHeader("cache-control", "no-cache");
request.AddHeader("Authorization", "OAuth oauth_consumer_key="(MY CONSUMER KEY)",oauth_signature_method="HMAC-SHA1",oauth_timestamp="1547481203",oauth_nonce="304ixaov43G",oauth_version="1.0",oauth_signature="(MY GENERATED SIGNATURE FROM POSTMAN)"");
IRestResponse response = client.Execute(request);
I'm working in .NET 4.6.2 and had binding issues when trying to reference the Square.Connect library which is Standard 2.0 so I'm trying to manually code things.
public ActionResult RequestToken(string code)
{
if (!string.IsNullOrEmpty(code))
{
string baseUrl = Request.Url.Scheme + "://" + Request.Url.Authority + Request.ApplicationPath.TrimEnd('/') + "/";
SquareUpRequest squareUpRequest = new SquareUpRequest()
{
client_id = "Application ID (Not sandbox)",
client_secret = "Personal Access Token",
code = code
};
var client = new RestSharp.RestClient(baseUrl);
var request = new RestSharp.RestRequest("https://connect.squareup.com/oauth/token", RestSharp.Method.POST);
request.RequestFormat = RestSharp.DataFormat.Json;
request.AddBody(squareUpRequest);
request.AddHeader("Authorization", "Client OAuthApplicationSecret");
var response = client.Execute(request);
}
return View();
}
I'm assuming that I can request a token many times. SquareUpRequest is a custom class.
Do you seen anything incorrect?
Wow. I just noticed after a few hours of hell that:
var request = new RestSharp.RestRequest("https://connect.squareup.com/oauth/token", RestSharp.Method.POST);
should be
var request = new RestSharp.RestRequest("https://connect.squareup.com/oauth2/token", RestSharp.Method.POST);
I want to get user email from user id (object identifier) from web api, but getting blank response while calling api for token. I am running this code from my Web API. Please help. Below is the code.
Given full permission to APIs
Getting Blank response in below line.
var responseBytes = await webClient.UploadValuesTaskAsync(url, "POST", requestParameters);
Below is code
var tenant = "tenant ID";
var clientID = "app ID";
// I've tried graph.microsoft.com and graph.microsoft.com/.default
var resource = "https://graph.microsoft.com";
var secret = "client secret";
string token;
using (var webClient = new WebClient())
{
var requestParameters = new NameValueCollection();
requestParameters.Add("scope", resource);
requestParameters.Add("client_id", clientID);
requestParameters.Add("grant_type", "client_credentials");
requestParameters.Add("client_secret", secret);
var url = "https://login.microsoftonline.com/{tenant}/oauth2/token";
webClient.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
var responseBytes = await webClient.UploadValuesTaskAsync(url, "POST", requestParameters);
var responseBody = Encoding.UTF8.GetString(responseBytes);
var jsonObject = Newtonsoft.Json.JsonConvert.DeserializeObject<Newtonsoft.Json.Linq.JObject>(responseBody);
token = jsonObject.Value<string>("access_token");
}
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Add("Authorization", "Bearer " + token);
var response = await client.GetAsync(new Uri("https://graph.microsoft.com/v1.0/user/" + ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier")));
Your error is here:
requestParameters.Add("scope", resource);
It needs to be resource rather than scope:
requestParameters.Add("resource", resource);
Can you help me understand what documentation or tutorial you followed to make this mistake? I have seen it happen before and I am trying to understand the patterns here.
The documentation and authentication flow you should be following is here.
I am trying to request token from the Twitter API based on my consumer key and consumer secret key. However I am getting a The remote server returned an error: (403) Forbidden which I am not sure why?
This is my attempt so far
//Get Request Token
string oauth_consumer_key = "<consumer key>";
string oauth_consumer_secret = "<consumer secret>";
Uri requestToken = new Uri("https://api.twitter.com/oauth2/token?oauth_consumer_key=" + oauth_consumer_key + "&oauth_consumer_secret=" + oauth_consumer_secret);
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(requestToken);
req.Method = "POST";
try
{
using (var response = req.GetResponse() as HttpWebResponse)
if (req.HaveResponse && response != null)
{
}
}
catch (WebException wex)
{
}
The code is incomplete however running through it I always seem to get a Forbidden exception?
If I post the URL request as follows, it works fine and returns the token
https://twitter.com/oauth/request_token?oauth_consumer_key=bidjtABOkF0b3mvw1UaHWDf7x&oauth_consumer_secret=qWO208QapZvckBoyWu3QET8uFnBXXlG3tSTWSS8oAOtoY8qwHD
Am I doing something wrong?
Solved my problem by using Task / Asyc and also adding authorization OAuth headers. Now able to get access token
Here is my solution:
public async Task<ActionResult> AccessToken()
{
var httpClient = new HttpClient();
var request = new HttpRequestMessage(HttpMethod.Post, "https://api.twitter.com/oauth2/token");
string oauth_consumer_key = "<consumer key>";
string oauth_consumer_secret = "<consumer secret>";
string url = "https://api.twitter.com/oauth2/token?oauth_consumer_key=" + oauth_consumer_key + "&oauth_consumer_secret=" + oauth_consumer_secret;
var customerInfo = Convert.ToBase64String(new UTF8Encoding()
.GetBytes(oauth_consumer_key + ":" + oauth_consumer_secret));
// Add authorization to headers
request.Headers.Add("Authorization", "Basic " + customerInfo);
request.Content = new StringContent("grant_type=client_credentials", Encoding.UTF8,
"application/x-www-form-urlencoded");
HttpResponseMessage response = await httpClient.SendAsync(request);
string json = await response.Content.ReadAsStringAsync();
var serializer = new JavaScriptSerializer();
dynamic item = serializer.Deserialize<object>(json);
ViewBag.access_token = item["access_token"];
return View();
}