0

I'm trying to write a program to access to a web site using basic authentication method.

Site address is: http://sv1.apple-media.in/

I used this code to read site content:

String username = "XXXX";
String password = "XXXX";
String url = "http://sv1.apple-media.in/";
WebRequest myReq = WebRequest.Create(url);
CredentialCache mycache = new CredentialCache();
mycache.Add(new Uri(url), "Basic", new NetworkCredential(username, password));
myReq.Credentials = mycache;
myReq.GetResponse();

But I always get this error:

System.Net.WebException was unhandled
   HResult=-2146233079
   Message=The remote server returned an error: (401) Unauthorized.
   Source=System
   StackTrace:
      at System.Net.HttpWebRequest.GetResponse()
      at IDMDownloadListAdderPlugin.Form1.button1_Click(Object sender, EventArgs e) in c:\Users\amir\Documents\Visual Studio 2012\Projects\IDMDownloadListAdderPlugin\IDMDownloadListAdderPlugin\Form1.cs:line 60
      at System.Windows.Forms.Control.OnClick(EventArgs e)
      at System.Windows.Forms.Button.OnClick(EventArgs e)
      at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
      at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
      at System.Windows.Forms.Control.WndProc(Message& m)
      at System.Windows.Forms.ButtonBase.WndProc(Message& m)
      at System.Windows.Forms.Button.WndProc(Message& m)
      at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
      at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
      at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
      at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
      at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
      at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
      at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
      at System.Windows.Forms.Application.Run(Form mainForm)
      at IDMDownloadListAdderPlugin.Program.Main() in c:\Users\amir\Documents\Visual Studio 2012\Projects\IDMDownloadListAdderPlugin\IDMDownloadListAdderPlugin\Program.cs:line 19
      at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
      at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
      at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
      at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
      at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
      at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
      at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
      at System.Threading.ThreadHelper.ThreadStart()
   InnerException:

When I log in to the web site using chrome browser, the header is:

Remote Address:31.3.247.107:80
Request URL:http://sv1.apple-media.in/
Request Method:GET
Status Code:200 OK
Request Headersview source
Accept:text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
Accept-Encoding:gzip,deflate,sdch
Accept-Language:en-US,en;q=0.8,fa;q=0.6
Authorization:Basic something
Cache-Control:max-age=0
Connection:keep-alive
Host:sv1.apple-media.in
User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko)                 Chrome/38.0.2125.111 Safari/537.36
Response Headersview source
Connection:keep-alive
Content-Encoding:gzip
Content-Type:text/html
Date:Tue, 11 Nov 2014 03:23:28 GMT
Server:nginx
Transfer-Encoding:chunked
Vary:Accept-Encoding

Can someone tell me what i do wrong please?

Thanks!

5
  • Quick note: you just posted your username and password to a public website. May want to change that... Commented Nov 10, 2014 at 16:58
  • No I changed them to XXXX. Do you mean anywhere else? Commented Nov 10, 2014 at 16:59
  • In the Authorization header. It is just a base64 encoded version of the username and password. en.wikipedia.org/wiki/Basic_access_authentication#Client_side (This is actually one way to answer your question - myReq.Headers.Add("Authorization", "Basic " + encoded);) Commented Nov 10, 2014 at 17:14
  • So you mean i should just encode username and password to base64 String? and thanks, edited my post. Commented Nov 10, 2014 at 17:35
  • That worked thanks!Just please post it to answers so I can mark it as answer. Thanks alot Commented Nov 10, 2014 at 17:49

1 Answer 1

3

Instead of using the NetworkCredential, you can add the header yourself. See Basic Authentication for the exact format.

// fixed encoding, but taken from http://stackoverflow.com/questions/25852551
string username = "Your username";
string password = "Your password";

// http://stackoverflow.com/questions/7242316/what-encoding-should-i-use-for-http-basic-authentication
var ISO_8859_1 = Encoding.GetEncoding("ISO-8859-1");
var svcCredentials = Convert.ToBase64String(ISO_8859_1.GetBytes(username + ":" + password));

myReq.Headers.Add("Authorization", "Basic " + svcCredentials);
Sign up to request clarification or add additional context in comments.

1 Comment

Instead of using UTF8 as the encoding you should prefer ISO-8859-1 as suggested here What encoding should I use for HTTP Basic Authentication?. So the code should change to Encoding.GetEncoding("ISO-8859-1").GetBytes(username + ":" + password)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.