自定义HttpModule,用于未登录用户,不弹出Windows认证窗口,而是跳转回SSO站点

2012年的一篇随笔记录,可以学习到如何自定义HttpModule,而具体里面针对需求开发的代码,可能未必能让大伙了解到什么,可快速扫描而过。

  1 using System;
  2 using System.Web;
  3  
  4 using System.Configuration;
  5 using System.Web.Configuration;
  6 using Microsoft.SharePoint;
  7 using System.Net;
  8 using System.Security.Principal;
  9  
 10 namespace WebApplication1.EventHandlers
 11 {
 12     /// <summary>
 13     /// Windows认证下实现URL重定向,如:
 14     /// 1、未登录用户,不弹出Windows认证窗口,而是跳转回SSO站点;
 15     /// 2、支持SharePoint匿名站点,暂时不支持文档库或列表库断开继承后匿名访问的情况
 16     /// </summary>
 17     public class SSORedirect : IHttpModule
 18     {
 19         public void Dispose()
 20         {
 21             //throw new NotImplementedException();
 22         }
 23  
 24         public void Init(HttpApplication context)
 25         {
 26             context.AuthenticateRequest += new EventHandler(context_AuthenticateRequest);
 27         }
 28  
 29         /// <summary>
 30         /// 当ASP.NET 运行时准备验证用户身份的时候引发这个事件
 31         /// </summary>
 32         /// <param name="sender"></param>
 33         /// <param name="e"></param>
 34         internal void context_AuthenticateRequest(object sender, EventArgs e)
 35         {
 36             try
 37             {
 38                 // 忽略POSTBack的请求
 39                 HttpContext context = HttpContext.Current;
 40                 if (context == null || context.Request.HttpMethod.ToUpper() == "POST")
 41                 {
 42                     return;
 43                 }
 44  
 45                 if (IsWindowsAuth())
 46                 {
 47                     string url = context.Request.Url.AbsolutePath.ToString().ToLower();//"/"
 48                     string fullUrl = context.Request.Url.OriginalString.ToString().ToLower();//"http://yxjt.contoso.com:80/"
 49  
 50                     string strSSOUrl = "/Test/Default.aspx";//ConfigurationManager.AppSettings["SSOUrl"];
 51                     if (!string.IsNullOrEmpty(strSSOUrl))
 52                     {
 53                         if (url.IndexOf(strSSOUrl.ToLower()) == -1)
 54                         {
 55                             if (!IsAnonymous(fullUrl))//是否为非匿名访问的页面
 56                             {
 57                                 if (!context.Request.IsAuthenticated && IsValidUrl(url))//是否为未登录用户,并且是需验证的有效的地址
 58                                 {
 59                                     context.Response.Redirect(strSSOUrl);
 60                                 }
 61                             }
 62                         }
 63                     }
 64                 }
 65             }
 66             catch (Exception ex)
 67             {
 68  
 69             }
 70         }
 71  
 72         /// <summary>
 73         /// 判断是否为Windows认证
 74         /// </summary>
 75         /// <returns>是否为Windows认证</returns>
 76         private bool IsWindowsAuth()
 77         {
 78             Configuration c = WebConfigurationManager.OpenWebConfiguration("/web.config");
 79             AuthenticationSection auth = (AuthenticationSection)c.GetSection("system.web/authentication");
 80             return auth.Mode == AuthenticationMode.Windows;
 81         }
 82  
 83         /// <summary>
 84         /// 判断是否为允许匿名访问的站点
 85         /// </summary>
 86         /// <param name="requestFullUrl">请求的地址,例如"http://yxjt.contoso.com:80/"</param>
 87         /// <returns>是否为允许匿名访问的站点</returns>
 88         private bool IsAnonymous(string requestFullUrl)
 89         {
 90             bool isAnonymous = false;
 91             requestFullUrl = requestFullUrl.Split(new char[] { '?' })[0];
 92  
 93             SPSecurity.RunWithElevatedPrivileges(delegate()
 94             {
 95                 SPSite site = new SPSite(requestFullUrl);//这里不要用using自动垃圾回收,否则抛异常
 96                 SPWeb web = site.OpenWeb();//关键写法
 97                 isAnonymous = web.AllowAnonymousAccess;
 98             });
 99             return isAnonymous;
100         }
101  
102         /// <summary>
103         /// 判断是否是有效的地址
104         /// </summary>
105         /// <param name="requestUrl">请求的地址,例如"/"</param>
106         /// <returns>是否是有效的地址</returns>
107         private bool IsValidUrl(string requestUrl)
108         {
109             bool isValidUrl = false;
110             requestUrl = requestUrl.Split(new char[] { '?' })[0];
111             int index = requestUrl.LastIndexOf(".");
112             if (index != -1)//是否包含.号
113             {
114                 isValidUrl = requestUrl.EndsWith(".aspx");//是否以.aspx结尾的url
115             }
116             else
117             {
118                 isValidUrl = true;
119             }
120             return isValidUrl;
121         }
122     }
123 }
原文地址:https://www.cnblogs.com/huangjianwu/p/4537400.html