ASP.NET HTTP Authorization Header

后端 未结 3 1241
悲哀的现实
悲哀的现实 2020-12-24 02:19

I would like to know why my asp.net application will not add the header to my post when it is named \'Authorization\' but will work fine when I change one character, say \"A

相关标签:
3条回答
  • 2020-12-24 02:39

    NetworkCredential is a good solution but the site you are calling has to handle an unauthorized with a 401 AND a WWW-Authenticate header in the response.

    Client:

    request.Credentials = new CredentialCache {{aUri, "Basic", new NetworkCredential(aUserName, aPassword)}};
    

    Server:

    Response.ClearContent();
    Response.StatusCode = 401;
    Response.AddHeader("WWW-Authenticate", "Basic");
    Response.End();
    

    This will result in 2 hits to the server. The initial call will go to the server without credentials. When the server responds with a 401 AND the WWW-Authenticate header (with the type of authentication required), the request will be resent with the credentials in the request.

    0 讨论(0)
  • 2020-12-24 02:42

    For HTTP Basic Authorization, you should be using the Credentials property.

    req.Credentials = new NetworkCredential("DDSServices", "jCole2011");

    This should do what you want. Rather than setting the Authorization header.

    0 讨论(0)
  • 2020-12-24 02:59

    I was ran into a question how to add Authentication/Credentials to the headers. I found the solution in the following way.

    string _auth = string.Format("{0}:{1}", "myUser","myPwd");
    string _enc = Convert.ToBase64String(Encoding.ASCII.GetBytes(_auth));
    string _cred = string.Format("{0} {1}", "Basic", _enc);
    req.Headers[HttpRequestHeader.Authorization] = _cred;
    

    Which gave me those headers I want (pasted Wireshark descriptions),

    Authorization: Basic bXlVc2VyOm15UHdk\r\n
    Credentials: myUser:myPwd

    0 讨论(0)
提交回复
热议问题