1. 程式人生 > >CAS統一登入認證(7): 非典型.net客戶端

CAS統一登入認證(7): 非典型.net客戶端

     所謂非典型,就是不是按官方指南,github 上有標準的.net cas客戶端demo  下載dotnet-cas-client-master 部署即可,這個是在web.config增加了攔截器,一是攔截軟體的登入驗證,二是使用.net和IIS本身內建的認證機制,而在實際做sso時,發現有些現有軟體並沒有使用這個認證機制,另外一個可能需求就是,做sso時不想太霸道,保留原來軟體的認證登入,只是靜靜的增加多一個sso認證途徑,這時,不對web.config做任何攔截修改,只是增加一個caslogin.aspx,訪問指向這個網頁時,才使用sso登入。當然,需要在未登入狀態時允許訪問這個頁面。

不多廢話,上原始碼,參考網上的程式碼,除錯通過c#程式碼,有個老專案是VB.net的,又翻譯成了VB.net原始碼,均除錯可用。

c# 原始碼:

    public partial class caslogin : System.Web.UI.Page
    {
        internal static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
        {
            return true;   //處理非ssl連線導致重定向次數過多
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(CheckValidationResult);
            string CASHOST = "https://author.linbsoft.com:8443/cas/";   //cas伺服器地址
            string tkt = Request.QueryString["ticket"];
            string service = Request.Url.GetLeftPart(UriPartial.Path);
            if (tkt == null || tkt.Length == 0)   //檢查未帶ticket,重定向到cas登入頁
            {
                string redir = CASHOST + "login?service=" + service;
                Response.Redirect(redir);
                return;
            }
            string validateurl = CASHOST + "serviceValidate?ticket=" + tkt + "&service=" + service;
            StreamReader Reader = new StreamReader(new WebClient().OpenRead(validateurl));   //根據ticket驗證取回使用者資訊
            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 netid = null;
            while (reader.Read())  //從返回資訊中讀取使用者賬號等
            {
                if (reader.IsStartElement())
                {
                    string tag = reader.LocalName;
                    if (tag == "user")
                        netid = reader.ReadString();
			//這裡可以讀取其它返回資訊
                }
            }
            reader.Close();
            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);  
            } 

        }
    }

 

VB.NET 原始碼:

    Public Class caslogin
        Inherits System.Web.UI.Page

        Protected Function CheckValidationResult(ByVal sender As Object, ByVal certificate As X509Certificate, ByVal chain As X509Chain, ByVal errors As SslPolicyErrors) As Boolean
            Return True    '處理非ssl連線導致重定向次數過多
        End Function


        Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
            ServicePointManager.ServerCertificateValidationCallback = New System.Net.Security.RemoteCertificateValidationCallback(AddressOf CheckValidationResult)
            Dim CASHOST As String = "https://author.linbsoft.com:8443/cas/";   ' cas伺服器地址
            Dim tkt As String = ""
            If Not Request.QueryString("ticket") Is Nothing Then    '檢查未帶ticket,重定向到cas登入頁
                tkt = Request.QueryString("ticket")
            End If
            Dim service As String = Request.Url.GetLeftPart(UriPartial.Path)
            If tkt = "" Or tkt.Length < 1 Then
                Dim redir As String = CASHOST + "login?service=" + service
                Response.Redirect(redir)
                Return
            End If
            Dim validateurl As String = CASHOST + "serviceValidate?ticket=" + tkt + "&service=" + service
            Dim Reader As StreamReader = New StreamReader(New WebClient().OpenRead(validateurl))     '根據ticket驗證取回使用者資訊
            Dim resp As String = Reader.ReadToEnd()
            Dim nt As NameTable = New NameTable()
            Dim nsmgr As XmlNamespaceManager = New XmlNamespaceManager(nt)
            Dim context As XmlParserContext = New XmlParserContext(Nothing, nsmgr, Nothing, XmlSpace.None)
            Dim myreader As XmlTextReader = New XmlTextReader(resp, XmlNodeType.Element, context)
            Dim netid As String = ""
            While (myreader.Read())   '從返回資訊中讀取使用者賬號等
                If (myreader.IsStartElement()) Then
                    Dim tag As String = myreader.LocalName
                    If (tag = "user") Then
                        netid = myreader.ReadString()
                    End If
			'這裡可以讀取其它返回資訊
                End If
            End While
            myreader.Close()  
            If (netid = "") Then     '伺服器拒絕驗證,未返回使用者資訊
                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)
            End If
        End Sub
    End Class