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

时间:2023-12-10 21:41:02

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

 using System;
using System.Web; using System.Configuration;
using System.Web.Configuration;
using Microsoft.SharePoint;
using System.Net;
using System.Security.Principal; namespace WebApplication1.EventHandlers
{
/// <summary>
/// Windows认证下实现URL重定向,如:
/// 1、未登录用户,不弹出Windows认证窗口,而是跳转回SSO站点;
/// 2、支持SharePoint匿名站点,暂时不支持文档库或列表库断开继承后匿名访问的情况
/// </summary>
public class SSORedirect : IHttpModule
{
public void Dispose()
{
//throw new NotImplementedException();
} public void Init(HttpApplication context)
{
context.AuthenticateRequest += new EventHandler(context_AuthenticateRequest);
} /// <summary>
/// 当ASP.NET 运行时准备验证用户身份的时候引发这个事件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
internal void context_AuthenticateRequest(object sender, EventArgs e)
{
try
{
// 忽略POSTBack的请求
HttpContext context = HttpContext.Current;
if (context == null || context.Request.HttpMethod.ToUpper() == "POST")
{
return;
} if (IsWindowsAuth())
{
string url = context.Request.Url.AbsolutePath.ToString().ToLower();//"/"
string fullUrl = context.Request.Url.OriginalString.ToString().ToLower();//"http://yxjt.contoso.com:80/" string strSSOUrl = "/Test/Default.aspx";//ConfigurationManager.AppSettings["SSOUrl"];
if (!string.IsNullOrEmpty(strSSOUrl))
{
if (url.IndexOf(strSSOUrl.ToLower()) == -)
{
if (!IsAnonymous(fullUrl))//是否为非匿名访问的页面
{
if (!context.Request.IsAuthenticated && IsValidUrl(url))//是否为未登录用户,并且是需验证的有效的地址
{
context.Response.Redirect(strSSOUrl);
}
}
}
}
}
}
catch (Exception ex)
{ }
} /// <summary>
/// 判断是否为Windows认证
/// </summary>
/// <returns>是否为Windows认证</returns>
private bool IsWindowsAuth()
{
Configuration c = WebConfigurationManager.OpenWebConfiguration("/web.config");
AuthenticationSection auth = (AuthenticationSection)c.GetSection("system.web/authentication");
return auth.Mode == AuthenticationMode.Windows;
} /// <summary>
/// 判断是否为允许匿名访问的站点
/// </summary>
/// <param name="requestFullUrl">请求的地址,例如"http://yxjt.contoso.com:80/"</param>
/// <returns>是否为允许匿名访问的站点</returns>
private bool IsAnonymous(string requestFullUrl)
{
bool isAnonymous = false;
requestFullUrl = requestFullUrl.Split(new char[] { '?' })[]; SPSecurity.RunWithElevatedPrivileges(delegate()
{
SPSite site = new SPSite(requestFullUrl);//这里不要用using自动垃圾回收,否则抛异常
SPWeb web = site.OpenWeb();//关键写法
isAnonymous = web.AllowAnonymousAccess;
});
return isAnonymous;
} /// <summary>
/// 判断是否是有效的地址
/// </summary>
/// <param name="requestUrl">请求的地址,例如"/"</param>
/// <returns>是否是有效的地址</returns>
private bool IsValidUrl(string requestUrl)
{
bool isValidUrl = false;
requestUrl = requestUrl.Split(new char[] { '?' })[];
int index = requestUrl.LastIndexOf(".");
if (index != -)//是否包含.号
{
isValidUrl = requestUrl.EndsWith(".aspx");//是否以.aspx结尾的url
}
else
{
isValidUrl = true;
}
return isValidUrl;
}
}
}