<appSettings>
    <!--是否启用单点登录接口-->
    <add key="IsStartCas" value="false"/>
    <!--Cas登录地址-->
    <add key="loginUrl" value="http://ys:3000/cas/login"/>
    <!--Cas验证地址-->
    <add key="validateUrl" value="http://ys:3000/cas/serviceValidate"/>
    <!--Cas注销地址-->
    <add key="logoutUrl" value="http://ys:3000/cas/logout"/>
  </appSettings>

using System;
using System.Web.Security;
using System.Web;
using System.Net;
using System.IO;
using System.Xml;
using System.Security.Principal;
using System.Configuration;
using System.Web.SessionState;

namespace LcSoftCard.CasModule
{
    /// <summary>
    /// Cas单点登录接口
    /// yisafe
    /// 2010-08-13
    /// </summary>
    public class SSOCasModule : IHttpModule, IReadOnlySessionState
    {
        //Return url coolie name
        protected const string ReturnUrl = "LcSoftCard.CasModule";
        public void Init(HttpApplication application)
        {
            string IsStartCas = ConfigurationManager.AppSettings.Get("IsStartCas");
            if (IsStartCas == "true")
            {
                application.AuthenticateRequest += (new EventHandler(this.Application_AuthenticateRequest));
                //application.PreRequestHandlerExecute += (this.context_PreRequesHandlerExecute);
            }
        }

private void Application_AuthenticateRequest(Object source, EventArgs e)
        {
            HttpApplication application = (HttpApplication)source;
            string casLogin = ConfigurationManager.AppSettings.Get("loginUrl");
            string casValidate = ConfigurationManager.AppSettings.Get("validateUrl");
            if (casLogin == null || casLogin.Length < 1 || casValidate == null || casValidate.Length < 1)
            {
                // trigger a server error if cashost is not set in the web.config
                application.Response.StatusCode = 500;
                return;
            }
            string cookieName = FormsAuthentication.FormsCookieName;
            HttpCookie authCookie = application.Request.Cookies[cookieName];
            if (authCookie != null)
            {
                FormsAuthenticationTicket authTicket = null;
                try
                {
                    authTicket = FormsAuthentication.Decrypt(authCookie.Value);
                }
                catch
                {
                    // TODO: Make a 500 error or go back to authentication
                    return;
                }

if (authTicket == null)
                {
                    // TODO: Make a 500 error or go back to authentication
                    return;
                }
                // create an identity objet
                FormsIdentity identity = new FormsIdentity(authTicket);
                // create a principal
                GenericPrincipal principal = new GenericPrincipal(identity, null);
                // attach the principal to tue context objet that will flow throughout the request.
                application.Context.User = principal;
            }
            else
            {
                // Check if we are back from CAS Authentication
                // Look for the "ticket=" string after the "?" in the URL when back from CAS
                string casTicket = application.Request.QueryString["ticket"];
                // The CAS service name is the page URL for CAS Server call back
                // so any query string is discard.
                string service = application.Request.Url.GetLeftPart(UriPartial.Path);
                if (casTicket == null || casTicket.Length == 0)
                {
                    // memorize the initial request query string
                    application.Response.Cookies[ReturnUrl].Value = application.Request.RawUrl;
                    // redirect to cas server
                    string redir = casLogin + "?service=" + service;
                    application.Response.Redirect(redir);
                    return;
                }
                else
                {
                    // Second pass (return from CAS server) because there is a ticket in the query string to validate
                    string validateurl = casValidate + "?ticket=" + casTicket + "&" + "service=" + service;
                    WebClient client = new WebClient();
                    StreamReader Reader = new StreamReader(client.OpenRead(validateurl));

// Put the validation response in a string
                    string resp = Reader.ReadToEnd();

// Some boilerplate to set up the parse of validation response.
                    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;

// A very dumb use of XML by looping in all tags.
                    // 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();
                                break;
                            }
                        }
                    }
                    reader.Close();

// If there was a problem, leave the message on the screen. Otherwise, return to original page.
                    if (netid == null)
                    {
                        application.Response.Write("Get Cas Configuration error!");
                    }
                    else
                    {
                        application.Response.Write("Bienvenue " + netid);
                        // create the authentication ticket and store the roles in the user data
                        LcSoftCard.BLL.TMasterFormsTicket bll = new LcSoftCard.BLL.TMasterFormsTicket();
                        LcSoftCard.Model.TMasterFormsTicket model = bll.GetModel(netid);
                        if (model.PersonId != Guid.Empty)
                        {
                            string UserData = model.PersonId + "|" + model.PersonNo + "|" + model.PersonName;
                            FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, model.MasterId.ToString(), DateTime.Now, DateTime.Now.AddMinutes(LcSoftCard.Service.AppConfig.SessionTimeOut), true, UserData);
                            // encrypt the ticket
                            string encryptedTicket = FormsAuthentication.Encrypt(ticket);
                            // create a cookie and use the encrypted ticket as data
                            authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
                            // add the cookie to the response cookie collection
                            application.Response.Cookies.Add(authCookie);

//// go the initial request URL
                            //string returnUrl;
                            //// if the return url cookie is lost, return to the default page
                            //if (application.Request.Cookies[ReturnUrl] == null)
                            //    returnUrl = application.Request.ApplicationPath;
                            //else
                            //    returnUrl = application.Request.Cookies[ReturnUrl].Value;

application.Response.Redirect(FormsAuthentication.DefaultUrl);
                        }
                        else
                        {
                            application.Response.Write("Error:system not " + netid);
                        }
                    }
                }
            }
        }

private void context_PreRequesHandlerExecute(Object source, EventArgs e)
        {
            HttpApplication application = (HttpApplication)source;
            System.Web.HttpContext.Current.Session["PersonNo"] = application.Context.User.Identity.Name;
        }

public void Dispose()
        {
        }
    }
}

.NET 单点登录的更多相关文章

  1. 著名ERP厂商的SSO单点登录解决方案介绍一

          SSO英文全称Single Sign On,单点登录.SSO是在多个应用系统中,用户只需要登录一次就可以访问所有相互信任的应用系统.它包括可以将这次主要的登录映射到其他应用中用于同一个用户 ...

  2. 看图理解JWT如何用于单点登录

    单点登录是我比较喜欢的一个技术解决方案,一方面他能够提高产品使用的便利性,另一方面他分离了各个应用都需要的登录服务,对性能以及工作量都有好处.自从上次研究过JWT如何应用于会话管理,加之以前的项目中也 ...

  3. 细说SSO单点登录

    什么是SSO? 如果你已知道,请略过本节! SSO核心意义就一句话:一处登录,处处登录:一处注销,处处注销.即:在多个应用系统中,用户只需要登录一次就可以访问所有相互信任的应用系统. 很多人容易把SS ...

  4. [原创]django+ldap+memcache实现单点登录+统一认证

    前言 由于公司内部的系统越来越多,为了方便用户使用,通过django进行了单点登录和统一认证的尝试,目前实现了django项目的单点登录和非django项目的统一认证,中间波折挺多,涉及的技术包括dj ...

  5. [原创]django+ldap实现单点登录(装饰器和缓存)

    前言 参考本系列之前的文章,我们已经搭建了ldap并且可以通过django来操作ldap了,剩下的就是下游系统的接入了,现在的应用场景,我是分了2个层次,第一层次是统一认证,保证各个系统通过ldap来 ...

  6. CAS FOR WINDOW ACTIVE DIRECTORY SSO单点登录

    一.CAS是什么? CAS(Central Authentication Service)是 Yale 大学发起的一个企业级的.开源的项目,旨在为 Web 应用系统提供一种可靠的单点登录解决方法(支持 ...

  7. 单点登录改进版-使用ajax分发cookie避免重定向轮询

    前言 继上一篇博文:可跨域的单点登录(SSO)实现方案[附.net代码]虽然实现了单点登录,也存在很多不合理的地方.很多热心的朋友也给出了很多指导性的意见,特别是 LoveCoder提出的意见. 在很 ...

  8. 可跨域的单点登录(SSO)实现方案【附.net代码】

    SSO简介 定义: 传统的单站点登录访问授权机制是:登录成功后将用户信息保存在session中,sessionId保存在cookie中,每次访问需要登录访问的资源(url)时判断当前session是否 ...

  9. .net 单点登录实践

    前言 最近轮到我在小组晨会来分享知识点,突然想到单点登录,准备来分享下如何实现单点登录,所以有了下文.实现方案以及代码可能写得不是很严谨,有漏洞的地方或者错误的地方欢迎大家指正. 刚开始头脑中没有思路 ...

  10. asp.net mvc 权限过滤和单点登录(禁止重复登录)

    1.权限控制使用controller和 action来实现,权限方式有很多种,最近开发项目使用控制控制器方式实现代码如下 /// <summary> /// 用户权限控制 /// < ...

随机推荐

  1. Mahout-Pearson correlation的实现

    计算公式: 并通过以下代码对Mahout in Action的结果进行了验证: 代码例如以下: ` package com.example.mahout; public class TestColl ...

  2. Delphi 模拟网站验证码(酷,把随机文字写道图片上)

    function TfrmLabelPages.PwdImg(img: Timage): string; var I,j,k: Integer; vPoint: TPoint; vLeft: Inte ...

  3. Linux内核参数信息(Oracle相关)

    命令行:vim  /etc/sysctl.conf 查看如下两行的设置值,这里是: kernel.shmall = 2097152 kernel.shmmax = 4294967295 如果系统默认的 ...

  4. ListView数据动态刷新

    在Android开发中用到ListView时,经常遇到要更改ListView内容的情形,比如删除或增加ListView中显示的条目,这里给大家提供一下思路:不论ListView要显示的对象是什么(如: ...

  5. 获取Exe文件版本信息的函数(使用GetFileVersionInfo得到TFileVersionInfo结构体,包含12项内容)

    Type   TFileVersionInfo   =   Record         FixedInfo:TVSFixedFileInfo;         {版本信息}         Comp ...

  6. thinkphp 3.2.3 入门示例

    原文:thinkphp3.2 1.安装WAMPServer,到D:\wamp\. 2.下载ThinkPHP3.2.3核心版.解压缩后,放到D:\wamp\www\MyWeb\.打开浏览器,输入网址:h ...

  7. [Android学习笔记]Bitmap,BitmapDrawable,BitmapFactory学习笔记

    Bitmap:图片文件的封装,可以看做是一张位图此类中的静态方法可以通过源Bitmap创建新的Bitmap对象此类封装了位图的一些信息Bitmap文档 BitmapFactory:一个工具类,用于创建 ...

  8. [Windows Phone]模仿魔兽3技能按钮SkillButton

    简介: 模仿魔兽3技能按钮,带CD效果.使用的时候可以当做普通按钮使用,同时也支持Binding. 音效紧耦合在控件内部,因为控件本身目的就是模拟魔兽3的技能按钮,所以不考虑音效的扩展. Demo结构 ...

  9. Cocos2d-x 3.1.1 lua-tests 开篇

    Cocos2d-x 3.1.1 lua-tests开篇   本篇博客打算从研究Cocos2d-x引擎提供的測试样例来写起,笔者针对Cocos2d-x 3.1.1这个版本号来介绍怎样来学习它给我们提供的 ...

  10. JavaScript 中的事件对象(读书笔记思维导图)

    在触发 DOM 上的某个事件时,会产生一个事件对象 event,这个对象中包含着所有与事件有关的信息.包括导致事件的元素.事件的类型以及其他与特定事件相关的信息.例如,鼠标操作导致的事件对象中,会包含 ...