SSO.cs 3.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Web;
  6. using System.Security.Cryptography.X509Certificates;
  7. using System.Net.Security;
  8. using System.Net;
  9. using System.IO;
  10. using System.Xml;
  11. namespace EMIS.Utility.SSO
  12. {
  13. public static class SSO
  14. {
  15. public static string SSOLogin()
  16. {
  17. string tkt = HttpContext.Current.Request.QueryString["ticket"];
  18. string service = HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path);
  19. // 如果没有 ticket,则跳转到 认证平台 的登录页面
  20. if (tkt == null || tkt.Length == 0)
  21. {
  22. string redir = Const.SSO_HOST + "login?" +
  23. "service=" + service;
  24. HttpContext.Current.Response.Redirect(redir, true);
  25. throw new Exception("登录失败,检测不到登录票据");
  26. }
  27. ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(CheckValidationResult);
  28. // 检验 ticket 是否有效
  29. string validateurl = Const.SSO_HOST + "serviceValidate?" +
  30. "ticket=" + tkt + "&" +
  31. "service=" + service;
  32. StreamReader Reader = new StreamReader(new WebClient().OpenRead(validateurl));
  33. string resp = Reader.ReadToEnd();
  34. NameTable nt = new NameTable();
  35. XmlNamespaceManager nsmgr = new XmlNamespaceManager(nt);
  36. XmlParserContext context = new XmlParserContext(null, nsmgr, null, XmlSpace.None);
  37. XmlTextReader reader = new XmlTextReader(resp, XmlNodeType.Element, context);
  38. string user = null;
  39. // 在 xml 中找 cas:user 标签,如果没有找到,表示出错了。
  40. while (reader.Read())
  41. {
  42. if (reader.IsStartElement())
  43. {
  44. string tag = reader.LocalName;
  45. if (tag == "user")
  46. user = reader.ReadString();
  47. }
  48. }
  49. reader.Close();
  50. // 如果没有找到 cas:user,输出错误提示。否则返回登录页面
  51. if (string.IsNullOrEmpty(user))
  52. {
  53. throw new Exception("登录失败,认证平台无法识别登录票据");
  54. }
  55. else
  56. {
  57. return user;
  58. }
  59. }
  60. private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
  61. { // 总是接受 认证平台 服务器的证书
  62. return true;
  63. }
  64. public static void SSOLogout()
  65. {
  66. string tkt = HttpContext.Current.Request.QueryString["ticket"];
  67. string redir = Const.SSO_HOST + "logout?ticket=" + tkt;
  68. //WebRequest request = WebRequest.Create(redir);
  69. WebRequest request = WebRequest.Create("http://portal.gdsspt.cn/c/portal/logout");
  70. request.Method = "POST";
  71. try
  72. {
  73. request.GetResponse();
  74. }
  75. catch (Exception ex)
  76. {
  77. string e = ex.ToString();
  78. }
  79. }
  80. }
  81. }