asp.net 实现一个简单CAS Server


根据下图所示,我们需要实现CASClient端得"拦截器",我们通过HttpModule实现,服务端需要两个页面,一个是登陆界面,一个途中第5步通过token获取的用户信息的页面或者ashx。
cas_protocol-1.jpg

1、客户端的代码和配置
新建一个类,代码如下:
HttpModule
需要在拦截所有请求,在web.config中配置
<httpModules>
..............
<add name="LoginMoudle" type="client.filter"/> //type由于写在项目中只需要namespace.class方式,如果放在dll中,需要加",dll文件名"
</httpModules>

2、CAS服务端代码
1)登陆页面

1     <form id="form1" runat="server" method="post" action="login.ashx">
2     <div>Login ID:<input type="text" id="loginid" name="loginid" /></div>
3     <div>Password:<input type="password" id="password" name="password" /></div>
4     <div><input type="hidden" id="continute_url" name="continute_url" value="<%=Request["continute_url"] %>"/></div>
5     <div><input type="submit" value="Login" /></div>
6     </form
其中continute_url是filer传来的

2)登陆代码

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Web;
 5 using System.Web.Services;
 6 
 7 namespace cas
 8 {
 9     [WebService(Namespace = "http://tempuri.org/")]
10     [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
11     public class login : IHttpHandler
12     {
13 
14         public void ProcessRequest(HttpContext context)
15         {
16             HttpRequest Request = context.Request;
17             string loginid = Request["loginid"];
18             string password = Request["password"];
19             string continute_url = Request["continute_url"];
20 
21             //用户登录验证.
22 
23             string token = DateTime.Now.Ticks.ToString();//登陆成功后 生成token方法,自己考虑,需唯一
24             //缓存token
25             context.Application[token] = "用户名"; //实际使用中存放用户信息类的实例
26             //转移
27             context.Response.Redirect(continute_url + "?token=" + token);
28         }
29 
30         public bool IsReusable
31         {
32             get
33             {
34                 return false;
35             }
36         }
37     }
38 }
39 

3)CAS端获取用户信息的页面
method GetUser

运行过程基本是这样的:用户访问网站,filer首先拦截判断session中用户信息,如果不为空放行,否则,转到CAS登陆界面,登陆界面登陆后,返回地址中夹带token.
网站后台通过get或者post方法使用token去获取用户信息。

最后网站程序通过Session["user"]获取用户信息,无需关心登陆的实现,这样我们就实现了一个简单单点登录系统了。

posted @ 2009-09-08 13:58  Liren  阅读(1041)  评论(1编辑  收藏  举报