C# HttpWebRequest - PreAuthenticate: Still returns 401 forbidden (HTTPS)
I would like to ask you for help with the following code I have quickly write, beucase I always get "403 FORBIDDEN".
HttpWebRequest pozadavek = (HttpWebRequest)WebRequest.Create("LINK THAT ASKS FOR AUTHLOGIN"); //https
System.IO.StreamReader stream = null;
System.String result = null;
public Form1()
{
InitializeComponent();
pozadavek.AuthenticationLevel = System.Net.Security.AuthenticationLevel.MutualAuthRequested;
pozadavek.Credentials = new NetworkCredential("NAME", "PASS");
pozadavek.PreAuthenticate = true;
}
private void Form1_Load(object sender, EventArgs e)
{
WebResponse webresponse = pozadavek.GetResponse(); //throws an exception:403 forbidden
stream = new Syste开发者_开发问答m.IO.StreamReader(webresponse.GetResponseStream());
result = stream.ReadToEnd();
this.webBrowser1.DocumentText = result;
}
The site you are trying to open requires Basic Authentication. Bottom line is, you need to include the username/password in base64 encoded with your request. Luckily, .Net does that for you. Construct your request like this:
var credCache = new CredentialCache();
credCache.Add(new Uri("https://is.vsfs.cz/auth"), "Basic",
new NetworkCredential("user", "pwd"));
var request = (HttpWebRequest)WebRequest.Create(uri);
request.Credentials = credCache;
Here's one article explaining in more detail how various auth schemes are handled in .Net.
This code works 4 me...
Uri address = new Uri("https://www.example.com");
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(address);
string authInfo = username + ":" +password;
authInfo = Convert.ToBase64String(Encoding.UTF8.GetBytes(authInfo));
request.Headers.Add("Authorization", "Basic " + authInfo);
NetworkCredential myCreds = new NetworkCredential(username, password);
request.Credentials = myCreds;
request.Method = WebRequestMethods.Http.Get;
request.AllowAutoRedirect = true;
request.Proxy = null;
精彩评论