Posts Tagged ‘authentication’
Consumir un WebService con autenticación básica desde .NET
El título describe bastante bien lo que vamos a solucionar en este post.
public class SecureWebService : ThirdPartyWebService { protected override WebRequest GetWebRequest(Uri uri) { HttpWebRequest webRequest = (HttpWebRequest)base.GetWebRequest(uri); NetworkCredential credentials = Credentials as NetworkCredential; if (credentials != null) { string authInfo = ((credentials.Domain != null) && (credentials.Domain.Length > 0) ? credentials.Domain + @"\" : string.Empty) + credentials.UserName + ":" + credentials.Password; authInfo = Convert.ToBase64String(Encoding.Default.GetBytes(authInfo)); webRequest.Headers["Authorization"] = "Basic " + authInfo; } return webRequest; } }
via.
Basic Authentication en HTTP Post
string uri = string.Empty, user = string.Empty, password = string.Empty, postData = string.Empty, responseData = string.Empty; string encodedAuthorization = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(user + ":" + password)); HttpWebRequest webRequest = WebRequest.Create(uri) as HttpWebRequest; webRequest.Method = "POST"; webRequest.ContentType = "application/x-www-form-urlencoded"; webRequest.Headers = new WebHeaderCollection(); webRequest.Headers.Add("Authorization: Basic "+encodedAuthorization); using (StreamWriter rw = new StreamWriter(webRequest.GetRequestStream())) { rw.Write(postData); } using (StreamReader sr = new StreamReader(webRequest.GetResponse().GetResponseStream())) { responseData = sr.ReadToEnd(); }