C# HttpWebRequest - PreAuthenticate: Still returns 401 forbidden (HTTPS)
10,835
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.
Author by
Snake
Updated on June 19, 2022Comments
-
Snake almost 2 years
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 System.IO.StreamReader(webresponse.GetResponseStream()); result = stream.ReadToEnd(); this.webBrowser1.DocumentText = result; }