I've got a problem while trying to connect to an elasticsearch API.
The API expect an bearer token, but the NEST lybrary only provides a basic authentication and I've got to pass a custom header as well. So, did anybody have to face this problem?? How to pass custom headers?!
Thanks
You can add headers that should be added to all requests on ConnectionSettings
var pool = new SingleNodeConnectionPool(new Uri("http://localhost:9200"));
var connectionSettings = new ConnectionSettings(pool)
.GlobalHeaders(new NameValueCollection
{
{ "Authorization", "Bearer fnoi3nfion3fn00jr0j1r0" }
});
var client = new ElasticClient(connectionSettings);
Actually I was getting a mistaken concept. Actually I'm interacting with an API wich encapsolate the elasticsearch and just use the elasticsearch query sintax, so I didn't need to use NEST, the elasticsear package, to connect with it. And I just got to interact it with a simple http call.
Anyway, thanks Russ
you can add any header to your request:
req.Headers.Add("CustomeKey", CustomeData);
Related
I am pretty much new to RestSharp and am bit confused about the below two code blocks (numbered).
var client = new RestClient("url"); // client
client.Authenticator = new HttpBasicAuthenticator("username", "password");
var request = new RestRequest(Method.GET);
request.AddHeader("authorization", string.Format("Basic {0}", "username:password"));
IRestResponse response = client.Execute(request);
when to use authentication in client section and when to use it in request section. If we add basic authenticator in client object itself then is it required to bind it in every request that we make?
It would be helpful if someone can explain or direct me to right contents.
when to use authentication in client section
When you use one client to issue multiple requests that all need the same authorization.
and when to use it in request section.
When you want to issue a single request that requires authorization.
If we add basic authenticator in client object itself then is it required to bind it in every request that we make?
No.
See also Authenticators on RestSharp's GitHub Wiki.
When setting up an application with TradeKing, you get:
A Consumer Key
A Consumer Secret
A Oauth Token
A Oauth Token Secret
For accessing TradeKing's API, that's apparently all you need to build personal applications. However, I can't find a way to build the correct Oauth headers in C#/.NET.
The examples seem fairly simple, like this Node.js sample. The Oauth library for Node.js takes care of generating the appropriate headers. There are similar samples for a few other languages, but they all seem to have libraries to build the proper header from the provided keys and tokens. I can't find a library to do this with C#/.NET.
I'm trying to wrap my head around what's going on in this SO question that builds the headers from scratch, but it's pretty advanced. I'm poking around in the ASP.NET Security repo, because they must be handling this somewhere. But I can't quite find what I'm looking for.
How can I generate an Oauth header from these keys with .NET?
There is an open source library on CodePlex that has some Oauth management classes set up.
I still need to go through it and take out what isn't necessary, but fortunately it doesn't depend on any other classes from the repo. Once I added it to my project, it was pretty easy to test the connection:
public async Task<IActionResult> MakeRequest()
{
string result;
var oauth = new Oauth.Manager();
// _tradeKing is a configuration object I set up to hold user secrets
oauth["consumer_key"] = _tradeKing.ConsumerKey;
oauth["consumer_secret"] = _tradeKing.ConsumerSecret;
oauth["token"] = _tradeKing.OauthToken;
oauth["token_secret"] = _tradeKing.OauthTokenSecret;
var url = "https://api.tradeking.com/v1/accounts.json";
var authzHeader = oauth.GenerateAuthzHeader(url, "GET");
var request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "GET";
request.Headers["Authorization"] = authzHeader;
var response = await request.GetResponseAsync();
using (var reader = new StreamReader(response.GetResponseStream()))
{
result = reader.ReadToEnd();
}
return Content(result);
}
There are some more instructions on how to use it from this SO post.
I'm having issues trying to access Azure Data Lake Store via the WebHDFS APIs using an HttpClient in .NET
This is my code:
using (var client = new HttpClient())
{
HttpRequestMessage message = new HttpRequestMessage(HttpMethod.Put, resourceUri);
message.Headers.Authorization = new AuthenticationHeaderValue("Bearer", _accessToken);
message.Content = new StringContent(JsonConvert.SerializeObject(body));
message.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
var result = await client.SendAsync(message);
var content = await result.Content.ReadAsStringAsync();
result.EnsureSuccessStatusCode();
}
Which returns me a 401 with this message: "The access token is not provided in the 'Authorization' header"
The weird thing is if I take the exact accessToken and resourceUri and put it in Postman it works fine (201).
I've added the application under Access control, and in the Data Explorer > Access tab, and have given full rights (Read, Write, Execute).
I even rewrote this using RestSharp yet the same error is given to me, I checked the JWT token it is definitely correct and returning data when I use it in Postman. It seems like the header is being stripped out somewhere.
This is driving me crazy, I can't figure out what I am doing wrong! Can anyone please help?
The issue seems to be related to a redirect that was happening that added an extra parameter added to the operation in the resource URI.
The parameter was "write=true". So I've updated the Resource URI to include the parameter.
i.e. for PUT operation "https://yourstore.azuredatalakestore.net/webhdfs/v1/xxx?op=CREATE&write=true"
Very weird behaviour but it works now.
I found one interesting feature in UWP and HttpClient (it also works with WebRequest) :
Any Http request sends "If-*" headers. I did experiment with UWP and WPF apps. I sent request to Azure file storage which doesn't support "If-" headers and will return Error 400 if headers will be sended. So here is my code:
HttpClient client = new HttpClient();
var response = await client.GetAsync("LINK_TO_AZURE_FILE_STORAGE_IMAGE");
Very simply, similar for two apps. Result - WPF app doesn't send "If-*" headers, UWP does. So It means that I'm not able to use File Storage in UWP apps, I just have Error 400.
My question is - can I disable this st...d caching ? Thanks for your attention
Yeah, while using HttpClient in UWP apps, it will automatically use the local HTTP cache by default. For the first time, you code should work. Then you will get 400 Error as in the first response, it contains cache data and all subsequent requests will use this cache by default like following:
To fix this issue, we can use Windows.Web.Http.HttpClient class with HttpBaseProtocolFilter class and HttpCacheControl class to disable the cache like following:
var filter = new Windows.Web.Http.Filters.HttpBaseProtocolFilter();
filter.CacheControl.ReadBehavior = Windows.Web.Http.Filters.HttpCacheReadBehavior.MostRecent;
filter.CacheControl.WriteBehavior = Windows.Web.Http.Filters.HttpCacheWriteBehavior.NoCache;
var httpClient = new Windows.Web.Http.HttpClient(filter);
var response = await httpClient.GetAsync(new Uri("LINK_TO_AZURE_FILE_STORAGE_IMAGE"));
To make this method work, we need make sure there is no local HTTP cache. As HttpCacheReadBehavior.MostRecent represents it will still use the local HTTP cache if possible. So we'd better uninstall the app first and do not use HttpClient client = new HttpClient(); in the app.
Update:
Starting from Windows Anniversary Update SDK, there is a new enum value NoCache added to HttpCacheReadBehavior enumeration. With a combination of ReadBehavior and WriteBehavior, we can implement a variety of cache-related behaviors. When we don't want to use local cache, we can just set the ReadBehavior to HttpCacheReadBehavior.NoCache like:
var filter = new Windows.Web.Http.Filters.HttpBaseProtocolFilter();
filter.CacheControl.ReadBehavior = Windows.Web.Http.Filters.HttpCacheReadBehavior.NoCache;
var httpClient = new Windows.Web.Http.HttpClient(filter);
Have you tried using the Remove method of the DefaultRequestHeaders property of the HttpClient class?
I'm using the new HttpClient class, part of the WCF REST Starter Kit, to authenticate to Google's Map Data service. I've got my ClientLogin authentication token, but I'm not sure how to take this instruction:
GET http://maps.google.com/maps/feeds/maps/userID/full
Authorization: GoogleLogin
auth="authorization_token"
and make it work in this code:
var auth = [myAuthToken]
var http = new HttpClient("http://maps.google.com/maps/feeds/maps/[myUserName]/full");
http.DefaultHeaders.Authorization = Microsoft.Http.Headers.Credential.CreateBasic("GoogleLogin", "auth=" + auth);
var response = http.Get();
The docs say: "the GET request requires an Authorization HTTP header, passing an AuthSub or GoogleLogin token." I have the token, I just don't know how to create that Authorization HTTP header correctly through that api. Anyone help?
Instead of using the CreateBasic static method, you can just pass the complete authorization header to the constructor of the Credential class. e.g.
client.DefaultHeaders.Authorization = new Credential("GoogleLogin auth=" + auth);