软件下载 | 资讯教程 | 最近更新 | 下载排行 | 一键转帖 | 发布投稿
您的位置:最火下载站 > 网络编程 > ASP.NET > ASP.NET 实现一个简单CAS

ASP.NET 实现一个简单CAS

CAS的原理,参照:http://bbs.liehuo.net/thread-4465-1-1.html 根据下图所示,我们需要实现CASClient端得"拦截器",我们通过HttpModule实现,服务端需要两个页面,一个是登陆界面,一个途中第5步通过token获取的用户信息的页面或者ashx。

烈火网(liehuo.net)提示:点击新窗口预览!

1、客户端的代码和配置
新建一个类,代码如下:
HttpModule
1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Web;
5 using System.Web.SessionState;
6 using System.Text;
7 using System.Net;
8 using System.IO;
9
10 namespace client
11 {
12 public class filter : IHttpModule, IRequiresSessionState
13 {
14 string login_url = "http://localhost:10888/Default.aspx";
15 string verify_url = "http://localhost:10888/method.ashx";
16
17 public void Dispose()
18 {
19
20 }
21
22 public void Init(HttpApplication context)
23 {
24 context.PreRequestHandlerExecute += new EventHandler(context_PreRequestHandlerExecute);
25 }
26
27 void context_PreRequestHandlerExecute(object sender, EventArgs e)
28 {
29 try
30 {
31 HttpApplication ha = (HttpApplication)sender;
32
33 HttpRequest Request = ha.Context.Request;
34 HttpResponse Response = ha.Context.Response;
35
36 string continue_url = Request.Url.AbsoluteUri;
37 string path = ha.Context.Request.Url.AbsolutePath;
38
39
40 string token = Request["token"];
41 if (!string.IsNullOrEmpty(token)) //这次请求是从CAS登陆后跳转而来
42 {
43 //使用POST连接CAS的method.ashx,通过token获取用户信息
44 string res = Post(verify_url, "token=" + token, "utf-8");
45 ha.Session["user"] = res;
46 Response.Redirect(ha.Session["continue_url"].ToString());
47 }
48
49 if ((ha.Session == null) || (ha.Session["user"] == null)) //通过Session判断登陆状态
50 {
51 ha.Session["continue_url"] = continue_url;
52 ha.Response.Redirect(login_url + "?continute_url=" + continue_url); //去登陆cas页面
53 }
54 }
55 catch (Exception ex)
56 {
57 (sender as HttpApplication).Response.Write(ex.Message);
58 }
59 }
60
61 public string Post(string postUrl, string postData, string chars_set)
62 {
63 Encoding encoding = Encoding.GetEncoding(chars_set);
64 HttpWebRequest Request = (HttpWebRequest)WebRequest.Create(postUrl);
65 CookieContainer cookieContainer = new CookieContainer();
66 Request.CookieContainer = cookieContainer;
67 Request.Method = "POST";
68 Request.ContentType = "application/x-www-form-urlencoded";
69 Request.AllowAutoRedirect = true;
70 byte[] postdata = encoding.GetBytes(postData);
71 using (Stream newStream = Request.GetRequestStream())
72 {
73 newStream.Write(postdata, 0, postdata.Length);
74 }
75 using (HttpWebResponse response = (HttpWebResponse)Request.GetResponse())
76 {
77 using (Stream stream = response.GetResponseStream())
78 {
79 using (StreamReader reader = new StreamReader(stream, encoding, true))
80 {
81 return reader.ReadToEnd();
82 }
83 }
84 }
85 }
86 }
87 }
88
需要在拦截所有请求,在web.config中配置
<httpModules>
..............
<add name="LoginMoudle" type="client.filter"/> //type由于写在项目中只需要namespace.class方式,如果放在dll中,需要加",dll文件名"
</httpModules>

相关阅读
网友评论
栏目导航
推荐软件