1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889 |
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Web;
- using System.Security.Cryptography.X509Certificates;
- using System.Net.Security;
- using System.Net;
- using System.IO;
- using System.Xml;
- namespace EMIS.Utility.SSO
- {
- public static class SSO
- {
- public static string SSOLogin()
- {
- string tkt = HttpContext.Current.Request.QueryString["ticket"];
- string service = HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path);
- // 如果没有 ticket,则跳转到 认证平台 的登录页面
- if (tkt == null || tkt.Length == 0)
- {
- string redir = Const.SSO_HOST + "login?" +
- "service=" + service;
- HttpContext.Current.Response.Redirect(redir, true);
- throw new Exception("登录失败,检测不到登录票据");
- }
- ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(CheckValidationResult);
- // 检验 ticket 是否有效
- string validateurl = Const.SSO_HOST + "serviceValidate?" +
- "ticket=" + tkt + "&" +
- "service=" + service;
- StreamReader Reader = new StreamReader(new WebClient().OpenRead(validateurl));
- string resp = Reader.ReadToEnd();
- NameTable nt = new NameTable();
- XmlNamespaceManager nsmgr = new XmlNamespaceManager(nt);
- XmlParserContext context = new XmlParserContext(null, nsmgr, null, XmlSpace.None);
- XmlTextReader reader = new XmlTextReader(resp, XmlNodeType.Element, context);
- string user = null;
- // 在 xml 中找 cas:user 标签,如果没有找到,表示出错了。
- while (reader.Read())
- {
- if (reader.IsStartElement())
- {
- string tag = reader.LocalName;
- if (tag == "user")
- user = reader.ReadString();
- }
- }
- reader.Close();
- // 如果没有找到 cas:user,输出错误提示。否则返回登录页面
- if (string.IsNullOrEmpty(user))
- {
- throw new Exception("登录失败,认证平台无法识别登录票据");
- }
- else
- {
- return user;
- }
- }
- private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
- { // 总是接受 认证平台 服务器的证书
- return true;
- }
- public static void SSOLogout()
- {
- string tkt = HttpContext.Current.Request.QueryString["ticket"];
- string redir = Const.SSO_HOST + "logout?ticket=" + tkt;
- //WebRequest request = WebRequest.Create(redir);
- WebRequest request = WebRequest.Create("http://portal.gdsspt.cn/c/portal/logout");
- request.Method = "POST";
- try
- {
- request.GetResponse();
- }
- catch (Exception ex)
- {
- string e = ex.ToString();
- }
- }
- }
- }
|