HttpRequest: pass through AuthLogin

2019-05-31 12:44发布

问题:

I would need to make a simple program that logs with given credentials to certain website and then navigate to some element (link). It is even possible (I mean this Authlogin thing)?

EDIT: SORRY - I am on my company machine and I cannot click on "Vote" or "Add comment" - the page says "Done, but with errors on page" (IE..). I do appreciate your answers and comments, you have helped me a lot!

回答1:

Main things to do are:

  1. Start using Fiddler to see what needs to be sent and in what way
  2. Assuming we're talking a normal web form you'll probably need to use a CookieContainer with your WebRequests in order to accept the cookies that come from the login request and then re-supply them when sending subsequent requests (such context is not automagically maintained by HttpWebRequest) :-

    CookieContainer _cookieContainer = new CookieContainer();
    ((HttpWebRequest)request).CookieContainer = _cookieContainer;
    


回答2:

yes. it is possible.

see following code:

        HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(uri);
        req.AuthenticationLevel = System.Net.Security.AuthenticationLevel.MutualAuthRequested;
        req.Credentials = new NetworkCredential("admin", "admin");
        req.PreAuthenticate = true;


回答3:

It will partly depend on how the login process is managed. Is this actually done via a web form? If so, you'll need to post the form, just as a normal browser would.

If it's done over HTTP authentication, you should be able to set the credentials in the web request, tell it to pre-authenticate, and all should be well.