2014-11-10 4 views
0

기본 인증 방법을 사용하여 웹 사이트에 액세스하기위한 프로그램을 작성하려고합니다.기본 인증을 사용하여 웹 사이트에 로그인 C#

사이트 주소는 다음과 같습니다 http://sv1.apple-media.in/

내가 사이트의 콘텐츠 읽기이 코드를 사용 :

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(); 

을하지만 난 항상이 오류를 얻을 :

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: 

내가 웹에 로그인 사이트가 크롬 브라우저를 사용하는 경우 헤더는 다음과 같습니다.

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 

누군가 내가 뭘 잘못했는지 말해 줄 수 있습니까?

감사합니다.

+0

요약 : 방금 공개 웹 사이트에 사용자 이름과 비밀번호를 게시했습니다. 그것을 바꿀 수도 있습니다 ... – Mitch

+0

아니요, XXXX로 바꿨습니다. 다른 곳을 의미합니까? –

+0

'Authorization' 헤더에 있습니다. 이것은 사용자 이름과 암호의 base64로 인코딩 된 버전 일뿐입니다. http://en.wikipedia.org/wiki/Basic_access_authentication#Client_side (실제로 이것은 myReq.Headers.Add ("Authorization", "Basic"+ encoded)) 질문에 대답하는 한 방법입니다.) – Mitch

답변

2

NetworkCredential을 사용하는 대신 헤더를 직접 추가 할 수 있습니다. 정확한 형식은 Basic Authentication을 참조하십시오.

// 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); 
+1

인코딩 대신 UTF8을 사용하는 대신 ISO-8859-1을 권장합니다. [HTTP 기본 인증에 어떤 인코딩을 사용해야합니까?] (http://stackoverflow.com/questions/7242316/what-encoding- http-basic 인증을 위해 i-use해야 함). 그래서 코드는'Encoding.GetEncoding ("ISO-8859-1")로 바뀌어야합니다. GetBytes (username + ":"+ password)' – Prateek

+0

@patreek이 저에게 효과적입니다. –

관련 문제