单点登录SSO for ASP.NET (二)
上一篇和大家分享了SSO的基本原理,这篇将主要和大家分享下.NET如何使用SSO。
最于应用系统要改为SSO方式,需要进行以下几步:
1、去掉原先的登录方式
2、获取相关证书
3、进行SSO配置
4、书写相关代码
我逐步解释下:
第一步说的有点废话,不过如果忘记的话,用户将是多么的生气。
第二步就是从统一身份认证系统那里得到你需要的证书。
第三部进行配置,
1) 将单点登录服务证书导入到IIS;
2) 下载DotNetCasClient.dll,添加至项目引用中:
下载地址:https://wiki.jasig.org/display/CASC/.Net+Cas+Client
记住,最后发布后bin文件夹中一定要包含DotNetCasClient.dll
3) 配置Web.config,在configuration节点下添加
- <membership>
- <providers>
- <clear/>
- <addname="AspNetSqlMembershipProvider"type="System.Web.Security.SqlMembershipProvider"connectionStringName="ApplicationServices"enablePasswordRetrieval="false"enablePasswordReset="true"requiresQuestionAndAnswer="false"requiresUniqueEmail="false"maxInvalidPasswordAttempts="5"minRequiredPasswordLength="6"minRequiredNonalphanumericCharacters="0"passwordAttemptWindow="10"applicationName="/"/>
- </providers>
- </membership>
- <profile>
- <providers>
- <clear/>
- <addname="AspNetSqlProfileProvider"type="System.Web.Profile.SqlProfileProvider"connectionStringName="ApplicationServices"applicationName="/"/>
- </providers>
- </profile>
- <roleManagerenabled="false">
- <providers>
- <clear/>
- <addname="AspNetSqlRoleProvider"type="System.Web.Security.SqlRoleProvider"connectionStringName="ApplicationServices"applicationName="/"/>
- <addname="AspNetWindowsTokenRoleProvider"type="System.Web.Security.WindowsTokenRoleProvider"applicationName="/"/>
- </providers>
- </roleManager>
- </system.web>
- <system.webServer>
- <modulesrunAllManagedModulesForAllRequests="true"/>
- </system.webServer>
第四步代码的书写,
引用命名空间:
- using System.IO;
- using System.Net;
- using System.Xml;
- using System.Security.Cryptography.X509Certificates;
添加代码:
- ServicePointManager.CertificatePolicy = newMyPolicy();
- //ServicePointManager.ServerCertificateValidationCallback += new System.Net.Security.RemoteCertificateValidationCallback();
- // Look for the "ticket=" after the "?" in the URL
- string tkt = (Request["ticket"] == null ? "" : Request["ticket"]).ToString();
- // This page is the CAS service=, but discard any query string residue
- string service = Request.Url.GetLeftPart(UriPartial.Path) == null ? "": Request.Url.GetLeftPart(UriPartial.Path).ToString();
- // First time through there is no ticket=, so redirect to CAS login
- if (tkt == null || tkt.Length == 0)
- {
- string redir = CASHOST + "login?service=" + service;
- Response.Redirect(redir);
- return"";
- }
- else
- {
- // Second time (back from CAS) there is a ticket= to validate
- string validateurl = CASHOST + "serviceValidate?" +
- "ticket=" + tkt + "&" +
- "service=" + service;
- StreamReader Reader = newStreamReader(newWebClient().OpenRead(validateurl));
- string resp = Reader.ReadToEnd();
- // I like to have the text in memory for debugging rather than parsing the stream
- // Some boilerplate to set up the parse.
- NameTable nt = newNameTable();
- XmlNamespaceManager nsmgr = newXmlNamespaceManager(nt);
- XmlParserContext context = newXmlParserContext(null, nsmgr, null, XmlSpace.None);
- XmlTextReader reader = newXmlTextReader(resp, XmlNodeType.Element, context);
- string netid = null;
- // A very dumb use of XML. Just scan for the "user". If it isn't there, its an error.
- while (reader.Read())
- {
- if (reader.IsStartElement())
- {
- string tag = reader.LocalName;
- if (tag == "user")
- netid = reader.ReadString();
- }
- }
- // if you want to parse the proxy chain, just add the logic above
- reader.Close();
- // If there was a problem, leave the message on the screen. Otherwise, return to original page.
- if (netid == null)
- {
- Label1.Text = "CAS returned to this application, but then refused to validate your identity.";
- }
- else
- {
- Session["UserName"] = netid;
- Label1.Text = "Welcome " + netid;
- FormsAuthentication.RedirectFromLoginPage(netid, false); // set netid in ASP.NET blocks
- }
- return netid;
- }
- publicclassMyPolicy : ICertificatePolicy
- {
- publicbool CheckValidationResult(
- ServicePoint srvPoint
- , X509Certificate certificate
- , WebRequest request
- , int certificateProblem)
- {
- //Return True to force the certificate to be accepted.
- returntrue;
- }
- }
这样四步走下来,基本就差不多了,另外string CASHOST ="https://sso.test.com:xxxx/casServer/";可以将sso服务器的地址写入web.config,从config读取便于以后维护。
刘国柱作于2012-09-20
原创文章转载请注明出处