BasicClient.cs 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. //
  2. // System.Net.BasicClient
  3. //
  4. // Authors:
  5. // Gonzalo Paniagua Javier ([email protected])
  6. //
  7. // (C) 2003 Ximian, Inc (http://www.ximian.com)
  8. //
  9. using System.Text;
  10. namespace System.Net
  11. {
  12. class BasicClient : IAuthenticationModule
  13. {
  14. public Authorization Authenticate (string challenge, WebRequest webRequest, ICredentials credentials)
  15. {
  16. if (credentials == null || challenge == null)
  17. return null;
  18. string header = challenge.Trim ();
  19. if (header.ToLower ().IndexOf ("basic") == -1)
  20. return null;
  21. return InternalAuthenticate (webRequest, credentials);
  22. }
  23. static Authorization InternalAuthenticate (WebRequest webRequest, ICredentials credentials)
  24. {
  25. HttpWebRequest request = webRequest as HttpWebRequest;
  26. if (request == null)
  27. return null;
  28. NetworkCredential cred = credentials.GetCredential (request.AuthUri, "basic");
  29. string userName = cred.UserName;
  30. if (userName == null || userName == "")
  31. return null;
  32. string password = cred.Password;
  33. string domain = cred.Domain;
  34. byte [] bytes;
  35. // If domain is set, MS sends "domain\user:password".
  36. if (domain == null || domain == "" || domain.Trim () == "")
  37. bytes = Encoding.Default.GetBytes (userName + ":" + password);
  38. else
  39. bytes = Encoding.Default.GetBytes (domain + "\\" + userName + ":" + password);
  40. string auth = "Basic " + Convert.ToBase64String (bytes);
  41. return new Authorization (auth);
  42. }
  43. public Authorization PreAuthenticate (WebRequest webRequest, ICredentials credentials)
  44. {
  45. return InternalAuthenticate ( webRequest, credentials);
  46. }
  47. public string AuthenticationType {
  48. get { return "Basic"; }
  49. }
  50. public bool CanPreAuthenticate {
  51. get { return true; }
  52. }
  53. }
  54. }