views:

606

answers:

1

Hello, 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;
    }
A: 

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.

Peter Lillevold
No, with either "true" and "false" it is the same. I am not sure whether it is the correct way, opening the link in browser will open an popup asking for username and password.
Snake
If "authentication" is done through a popup it is initially enforced clientside. Your request will never see that. It sounds like the site is using some sort of forms authentication. Perhaps you can get a direct url to the login page, but even then using the Credentials property will probably not work, you'll have to send username/pwd to the page using a POST request.
Peter Lillevold
Oh, I can see there is "https". I have changed the URI in the program and now get 401...any ideas please?
Snake
401 (http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html) still means you are not authorized. You should get a url directly to the login page and construct a POST that the page will accept.
Peter Lillevold
But how can I get it? You can take a look:https://is.vsfs.cz/auth
Snake
Yes, that made it clearer. I've updated my answer!
Peter Lillevold
Thank you very much!
Snake