我们有一个 ASP.NET MVC 4 Intranet 应用程序。我们正在使用 Windows 身份验证,这方面工作正常。使用用户的凭据,我们可以从 Web 应用程序访问这些凭据。
然而,我们真正想要的是某种混合模式。我们希望从浏览器获取用户的凭据,但我们还想验证用户是否在我们应用程序的数据库中。如果用户在数据库中,那么他们可以继续。如果不是,我们希望将他们重定向到一个页面,要求提供备用凭据。我现在所做的是,在Global.asax.cs
,我有一个Application_AuthenticateRequest
方法,我正在检查用户是否经过身份验证。如果他们是,并且他们的 cookie 信息没有反映他们已登录系统的事实,那么我将他们登录并设置一些包含用户信息的 cookie。如果他们没有经过身份验证,我会将他们重定向到登录页面。由于涉及公司政策的原因,我们无法使用 AD 角色,因此我们需要使用数据库进行额外的身份验证。
我正在猜测Application_AuthenticateRequest
不是这样做的地方,但也许是。但我们基本上需要一个地方来过滤身份验证请求。但此外,这种实现还导致我遇到另一个问题:
我们的应用程序中有某些允许匿名访问的 URL。我已经添加<location>
为这些标记到 web.config。问题是,当匿名调用这些时,它会Application_AuthenticateRequest
并尝试将用户登录到数据库中。现在,我可以将代码添加到Application_AuthenticateRequest
处理这些 URL,这就是我目前的计划,但如果我要写Application_AuthenticateRequest
不是做这件事的地方,那么我宁愿现在就解决,而不是以后再解决。
为此,您需要使用操作过滤器。您可以像这样扩展 AuthorizeAttribute:
public class MyAuthorizeAttribute : AuthorizeAttribute
{
private UnitOfWork _unitOfWork = new UnitOfWork();
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
var isAuthorized = false;
var username = httpContext.User.Identity.Name;
// Some code to find the user in the database...
var user = _unitOfWork.UserRepository.Find(username);
if(user != null)
{
isAuthorized = true;
}
return isAuthorized;
}
public override void OnAuthorization(AuthorizationContext filterContext)
{
if (filterContext == null)
{
throw new ArgumentNullException("filterContext");
}
if (AuthorizeCore(filterContext.HttpContext))
{
SetCachePolicy(filterContext);
}
else
{
// If not authorized, redirect to the Login action
// of the Account controller...
filterContext.Result = new RedirectToRouteResult(
new System.Web.Routing.RouteValueDictionary {
{"controller", "Account"}, {"action", "Login"}
}
);
}
}
protected void SetCachePolicy(AuthorizationContext filterContext)
{
// ** IMPORTANT **
// Since we're performing authorization at the action level,
// the authorization code runs after the output caching module.
// In the worst case this could allow an authorized user
// to cause the page to be cached, then an unauthorized user would later
// be served the cached page. We work around this by telling proxies not to
// cache the sensitive page, then we hook our custom authorization code into
// the caching mechanism so that we have the final say on whether a page
// should be served from the cache.
HttpCachePolicyBase cachePolicy = filterContext.HttpContext.Response.Cache;
cachePolicy.SetProxyMaxAge(new TimeSpan(0));
cachePolicy.AddValidationCallback(CacheValidationHandler, null /* data */);
}
public void CacheValidationHandler(HttpContext context,
object data,
ref HttpValidationStatus validationStatus)
{
validationStatus = OnCacheAuthorization(new HttpContextWrapper(context));
}
}
然后,您可以在控制器级别或操作级别使用此属性,如下所示:
[MyAuthorize]
public ActionResult SomeAction()
{
// Code that is supposed to be accessed by authorized users only
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)