/*
Kooboo is a content management system based on ASP.NET MVC framework. Copyright 2009 Yardi Technology Limited.
This program is free software: you can redistribute it and/or modify it under the terms of the
GNU General Public License version 3 as published by the Free Software Foundation.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with this program.
If not, see http://www.kooboo.com/gpl3/.
*/
//http://weblogs.asp.net/jigardesai/archive/2008/10/30/authorization-in-asp-net-mvc-using-xml-configuration.aspx
using System;
using System.Collections.Generic;
using System.Web.Routing;
using System.Web;
using System.Security;
namespace Everest.Library.Mvc.Authorization{
/// <summary>
/// Authorization Mapping Modele
/// </summary>
public class AuthorizationMappingModule : IHttpModule
{
#region IHttpModule Members
/// <summary>
/// Disposes of the resources (other than memory) used by the module that implements <see cref="T:System.Web.IHttpModule"/>.
/// </summary>
public void Dispose()
{
}
/// <summary>
/// Inits the specified app.
/// </summary>
/// <param name="app">The app.</param>
public void Init(HttpApplication app)
{
app.AuthorizeRequest += new EventHandler(OnAuthorizeRequest);
}
void OnAuthorizeRequest(object sender, EventArgs e)
{
HttpContext context = ((HttpApplication)sender).Context;
RouteData routeData = RouteTable.Routes.GetRouteData(new HttpContextWrapper(context));
if (routeData != null && !(routeData.RouteHandler is StopRoutingHandler))
{
string controller = routeData.GetRequiredString("controller");
string action = routeData.GetRequiredString("action");
IMVCAuthorizer authorizer = GetMVCAuthorizer();
if (!authorizer.IsAuthorized(controller, action, context.User))
{
//string message = string.Format("User {0} does not have permission to access {1} on {2}"
// , context.User.Identity.Name, action, controller);
//System.Diagnostics.Trace.TraceInformation(message);
//throw new SecurityException(message);
OnUnathorized(context, controller, action);
}
}
}
protected virtual void OnUnathorized(HttpContext context, string controller, string action)
{
System.Web.Security.FormsAuthentication.RedirectToLoginPage();
context.Response.End();
}
IMVCAuthorizer GetMVCAuthorizer()
{
string key = "IMCVAuthorizerCacheKey";
IMVCAuthorizer rVal = null;
if (HttpContext.Current.Cache[key] != null)
{
rVal = (IMVCAuthorizer)HttpContext.Current.Cache[key];
}
else
{
AuthorizationMappingSection settings = AuthorizationMappingSection.GetSettings();
rVal = Activator.CreateInstance(Type.GetType(settings.Type)) as IMVCAuthorizer;
rVal.Initilize(settings.ConnectionString);
HttpContext.Current.Cache.Insert(key, rVal, rVal.CacheDependency);
}
return rVal;
}
#endregion
}
}
|