Forcing Basic Authentication in WebRequest

后端 未结 4 677
春和景丽
春和景丽 2020-12-02 11:57

I am integrating web service that will use an HTTP-POST to request and retrieve data. The remote server requires basic authentication as per RFC 2617

My attempts to

4条回答
  •  情深已故
    2020-12-02 12:36

    Improving a little bit on samuel-jack's accepted answer. Instead of using the default encoding "ISO-8859-1" should be used as mentioned in this answer What encoding should I use for HTTP Basic Authentication?

    So the code would look like this:

    public void SetBasicAuthHeader(WebRequest request, String userName, String userPassword)
    {
        string authInfo = userName + ":" + userPassword;
        authInfo = Convert.ToBase64String(Encoding.GetEncoding("ISO-8859-1").GetBytes(authInfo));
        request.Headers["Authorization"] = "Basic " + authInfo;
    }
    

提交回复
热议问题