Cannot send authentication in header of project - c#

So basically I'm working on integrating a web API into my project from an externally hosted source.. But the xml is stored behind basic authentication. So I've been advised that I need to parse some authentication into the header of my HTTP request when contacting the location of the XML.
Here's what I'm working with at the moment:
I've created a controller, my code is as follows:
namespace com.tortoise.Controllers
{
public class VebraController : ApiController
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("url");
string username = "user";
string password = "password";
string usernamePassword = ("username + : + password");
CredentialCache cache = new CredentialCache();
new cache.add Uri(url), "Basic", new class NetworkCredential(username, password));
request.Credentials = cache;
request.Headers.Add("Authorization", "Basic " // <- space here.
+ Convert.ToBase64String()(new Int64 ASCIIEncoding().GetBytes (usernamePassword));
// Get the token from the response:
string token = response.GetResponseHeader("Token");
}
Any help is great. I'm receiving errors in CredentialCache, ASCIIEncoding, ToBase64String(), GetBytes() and GetResponseHeader().

Alright, I have fixed your code a bit. It should compile now, assuming you have actually declared the variables you are using. I can't do that for you. Please read the comments. You seem to need a lot of practice with C# syntax and the language in general, you had a lot of invalid C# in there. Hope this helps.
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
string username = "user";
string password = "password";
//here I am declaring the NetworkCredentials. You do not need to put 'new class'
NetworkCredential myCredentials = new System.Net.NetworkCredential(username,password);
string usernamePassword = (username + password); //I assume you meant to concatenate them
CredentialCache cache = new CredentialCache();
cache.Add((Uri)url, "Basic", myCredentials); //you must declare url, not sure what you want it to be
request.Credentials = cache;
request.Headers.Add("Authorization", "Basic " // <- space here.
+ Convert.ToBase64String(Encoding.ASCII.GetBytes(usernamePassword)); //fixed this
// Get the token from the response:
string token = response.GetResponseHeader("Token"); //you need to declare response somewhere

Related

Why am I not being able to add basic Authorization in SOAP header?

myAPI is the name of a web service reference I added to my project and I am trying to send Basic Authorization into the header of the SOAP request using C# but it’s not happening no matter what method I try.
I read a lot online and ended up with the following ways but none seem to work with mine.
What I've tried:
Method 1: no error but does nothing
NetworkCredential netCredential = new NetworkCredential("un", "pw");
Uri uri = new Uri(resol.Url);
ICredentials credentials = netCredential.GetCredential(uri, "Basic");
myAPI.Credentials = credentials;
myAPI.PreAuthenticate = true;
Method 2: (FYI ResolvingBinding (below) basically consists of all my method which comes from the service reference myAPI) but the problem is : "client" does not have any definition for InnerChannel and ClientCredential so this method fails too
myAPI.ResolvingBinding client = new myAPI.ResolvingBinding();
using (OperationContextScope scope = new OperationContextScope(client.InnerChannel))
{
var httpRequestProperty = new HttpRequestMessageProperty();
httpRequestProperty.Headers[System.Net.HttpRequestHeader.Authorization] = "Basic " +
Convert.ToBase64String(Encoding.ASCII.GetBytes(client.ClientCredentials.UserName.UserName + ":" +
client.ClientCredentials.UserName.Password));
OperationContext.Current.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = httpRequestProperty;
client.DoSomething();
}
My ultimate end goal is to encode username:password into base 64 which I tried in the second example.
How do I go about resolving this? Please feel free to add a comment/leave a suggestion or point out mistakes I might've overlooked.
This code should add your basic authentication to your header
var plainTextBytes = System.Text.Encoding.UTF8.GetBytes(<userId> + ":" +<pw>);
string val = System.Convert.ToBase64String(plainTextBytes);
string textValue = "Basic " + val;
httpRequestProperty.Headers.Add("Authorization", textValue);

How to send authentication header in ASP.Net for set of web request

I am developing ASP.net application which consumes REST services with ASP.Net Web API. I am trying to use Basic authentication for my website. I plan to use it with SSL once I complete Basic authentication.
Currently on Login button click I am sending Auth header using Base64 encoding of username and password as shown below:
string responseData = string.Empty;
string authToken = string.Empty;
string loginInstance = url;
// Create request.
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(loginInstance);
request.Method = "POST";
request.ContentType = "application/json";
request.CookieContainer = new CookieContainer();
String username = txtUserName.Text;
String password = txtPassword.Text;
String encoded = System.Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(username + ":" + password));
request.Headers.Add("Authorization", "Basic " + encoded);
request.ContentLength = 0;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream(), System.Text.Encoding.UTF8);
String resultData = reader.ReadToEnd();
bool result = false;
result = Convert.ToBoolean(resultData);
return result;
I assume I will need to send authentication header to all of those web api requests that needs to be secure and pass through authentciation.
Is there a way to attach authentication header to every request that I send or even to a set of requests?
Please note: most of the Web API requests are invoked through JQuery.
Also please let me know if this is not recommended approach of implementation.
Regards,
Abhilash
Have you try like this :
WebRequest request = (HttpWebRequest)WebRequest.Create("https://yoururl");
request.Headers.Add(HttpRequestHeader.Authorization, "Basic " + Convert.ToBase64String(System.Text.ASCIIEncoding.ASCII.GetBytes("user:password")));
basic http authentication in asp.net web api using message handlers.
http://www.piotrwalat.net/basic-http-authentication-in-asp-net-web-api-using-message-handlers/
Can you try with below code inplace of "request.Headers.Add("Authorization", "Basic " + encoded);" .
request.Headers.Add(HttpRequestHeader.Authorization, "Basic " +
Convert.ToBase64String(System.Text.ASCIIEncoding.ASCII.GetBytes("user:password")));
I believe you can just add
request.PreAuthenticare = true
You may look for HttpWebRequest.Credentials Property.
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(loginInstance);
request.Credentials = CredentialCache.DefaultCredentials;
Above example contains the credentials of the currently logged on user.
"The Credentials property can be either a NetworkCredential, in which case the user, password, and domain information contained in the NetworkCredential object is used to authenticate the request, or it can be a CredentialCache".
MSDN Reference

REST C# Get List Items

I am completely new to REST API.
I would like to retrieve ListItems in xml format from an external site in C#.
I have got the username and password for the site (which uses Mixed authentication by the way).
HttpWebRequest endpointRequest = (HttpWebRequest)HttpWebRequest.Create("https://<site>/_api/web/lists");
endpointRequest.Method = "GET";
endpointRequest.Accept = "application/atom+xml";
//endpointRequest.Headers.Add("Authorization", "Bearer " + accessToken);
endpointRequest.Headers["Authorization"] = "Basic " + Convert.ToBase64String(Encoding.Default.GetBytes("<domain>\\<username>:<password>"));
HttpWebResponse endpointResponse = (HttpWebResponse)endpointRequest.GetResponse();
I am using this piece of code that I found on MSDN.
Would anybody please be kind enough to tell me how do I get an access token?
Why am I getting 403 Forbidden error?
I think you can better use the NetworkCredential class:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
NetworkCredential credentials = new NetworkCredential("testuser", "testpass");
request.Credentials = credentials;
No need to send the Authorization header
When I have to use REST API I use Tiny.RestClient 1
In your case you have to write the call like that :
var client = new TinyRestClient(new HttpClient(), "https://<site>/_api/");
client.GetRequest("web/lists")
Hopes that help.
WithBasicAuthentication("username", "password").
ExecuteAsync();

HTTP Basic Auth for Diigo using C#: How to read response?

I am (trying) to develop a WPF (C#) app that just gets (or at least is supposed to get) my saved bookmarks at Diigo.com profile. The only helpful page i found is this . It says i have to use HTTP Basic authetication to get my self authenticated and make requests then. But don't understand how C# handles it!. The only solution i came up with below just prints entire HTML source to console window.
string url = "http://www.diigo.com/sign-in";
WebRequest myReq = WebRequest.Create(url);
string usernamePassword = "<username>:<password>";
CedentialCache mycache = new CredentialCache();
mycache.Add(new Uri(url), "Basic", new NetworkCredential("username", "password"));
myReq.Credentials = mycache;
myReq.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(new ASCIIEncoding().GetBytes(usernamePassword)));
//Send and receive the response
WebResponse wr = myReq.GetResponse();
Stream receiveStream = wr.GetResponseStream();
StreamReader reader = new StreamReader(receiveStream, Encoding.UTF8);
string content = reader.ReadToEnd();
Console.Write(content);
Here username and password are hardcoded but of course they'll come from some txtUsername.Text thing. And after that how am i going to read the JSON response and parse it?
What is that i need to do to get my app or myself HTTP basic authenticated?
Any help or suggestion is welcome!
If you're trying to talk to a service, you probably want to use the Windows Communication Foundation (WCF). It's designed specifically to solve the problems associated with communicating with services, such as reading/writing XML and JSON, as well as negotiating transports mechanisms like HTTP.
Essentially, WCF will save you doing all of the "plumbing" work of working with HttpRequest objects and manipulating strings. Your problems have already been solved by this framework. Use it if you can.
Ok i solved the problem after some (not really some) effort. Code below gets the JSON response from server which can then be parsed using any preferred method.
string key = "diigo api key";
string username = "username";
string pass = "password";
string url = "https://secure.diigo.com/api/v2/";
string requestUrl = url + "bookmarks?key=" + key + "&user=" + username + "&count=5";
HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create(requestUrl);
string usernamePassword = username + ":" + pass;
myReq.Timeout = 20000;
myReq.UserAgent = "Sample VS2010";
//Use the CredentialCache so we can attach the authentication to the request
CredentialCache mycache = new CredentialCache();
//this perform Basic auth
mycache.Add(new Uri(requestUrl), "Basic", new NetworkCredential(username, pass));
myReq.Credentials = mycache;
myReq.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(new ASCIIEncoding().GetBytes(usernamePassword)));
//Send and receive the response
WebResponse wr = myReq.GetResponse();
Stream receiveStream = wr.GetResponseStream();
StreamReader reader = new StreamReader(receiveStream, Encoding.UTF8);
string content = reader.ReadToEnd();
Console.Write(content);
content is the JSON response returned from server
Also this link is useful for getting started with api.

C# SSL Basic Access Authentication

I want to request reports from a third party and they require "Basic Access Authentication" via POST:
Your client application must use Basic Access Authentication
to send the user name and password.
Can someone point me in the right direction?
Edit: I did see this post but there are two answers and I'm not sure if thats what I need to do or which one is the preferred method.
Assuming you use a WebRequest, you attach a CredentialCache to your request:
NetworkCredential nc = new NetworkCredential("user", "password");
CredentialCache cc = new CredentialCache();
cc.Add("www.site.com", 443, "Basic", nc);
WebRequest request = WebRequest.Create("https://www.site.com");
request.Credentials = cc;
request.PreAuthenticate = true;
request.Method = "POST";
// fill in other request properties here, like content
WebResponse respose = request.GetResponse();
The basic gist is like this:
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
request.Method = WebRequestMethods.Http.Get;
request.Credentials = new NetworkCredential(username, password);
but sometimes there are issues with using request credentials, the alternative is add the authentication data in request headers
string authInfo = username + ":" + password;
authInfo = Convert.ToBase64String(Encoding.Default.GetBytes(authInfo));
request.Headers["Authorization"] = "Basic " + authInfo;
for more details see this blog post
http://charlie.cu.cc/2012/05/how-use-basic-http-authentication-c-web-request/

Categories