2009-02-16 28 views
12

¿Cómo creo un atributo personalizado para extender el atributo Authorize existente en MVC?asp.net mvc Agregar al atributo AUTORIZAR

+0

Por favor, agregue más detalles, ¿qué es exactamente lo que quiere extender? –

+0

por ahora solo quiero poder redireccionar a la página correcta en lugar de a la página de inicio predeterminada. – zsharp

+5

Puede actualizar su pregunta para que todos puedan saber lo que necesita. –

Respuesta

17

Derive su clase de AuthorizeAttribute. Reemplazar el método OnAuthorization. Agregue y configure un CacheValidationHandler.

public void CacheValidationHandler(HttpContext context, 
            object data, 
            ref HttpValidationStatus validationStatus) 
{ 
    validationStatus = OnCacheAuthorization(new HttpContextWrapper(context)); 
} 


public override void OnAuthorization(AuthorizationContext filterContext) 
{ 
    if (filterContext == null) 
    { 
     throw new ArgumentNullException("filterContext"); 
    } 

    if (AuthorizeCore(filterContext.HttpContext)) 
    { 
     ... your custom code ... 
     SetCachePolicy(filterContext); 
    } 
    else if (!filterContext.HttpContext.User.Identity.IsAuthenticated) 
    { 
     // auth failed, redirect to login page 
     filterContext.Result = new HttpUnauthorizedResult(); 
    } 
    else 
    { 
     ... handle a different case than not authenticated 
    } 
} 


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 */); 
} 
+0

bien, pero ¿cómo puedo redireccionar correctamente a la última página? – zsharp

+0

¿Cómo puedo hacer que esto funcione con Roles? Funciona bien ahora, pero parece que los roles no funcionan. Además, AuthorizeCore sigue mostrando false incluso cuando el usuario está autenticado, lo que significa que SetCachePolicy() nunca se ejecuta. –

+0

@Nick - Desde entonces he blogueado sobre la mejora de los aspectos de manejo de caché: http://farm-fresh-code.blogspot.com/2011/03/revisiting-custom-authorization-in.html – tvanfosson

3
public class CoolAuthorizeAttribute : AuthorizeAttribute 
{ 
} 
10

No necesita extender este atributo, web.config es suficiente. Por favor, lea acerca de forms Element for authentication. Presta atención en DefaultUrl. Esto es algo que necesitas

<system.web> 
    <authentication mode="Forms"> 
    <forms defaultUrl="YourUrlGoesHere"/> 
    </authentication> 
</system.web> 
+0

pero eso no es dinámico. cambios en la url – zsharp

+7

Hm, ¿por qué no especificar todos los requisitos antes de que uno dé la solución? –

+1

¡Noo! Esto es completamente incorrecto: http://blogs.msdn.com/b/rickandy/archive/2010/08/24/securing-your-mvc-application.aspx – bplus

0

sugiero que si lo que desea es ampliar el actual AuthorizeAttribute y añadir su propia autorización en la parte superior de la que, en lugar de anular OnAuthorization simplemente anular AuthorizeCore y añadir su condición MyCustomAuthorizationHolds a ella.

public class CustomAuthorizeAttribute : AuthorizeAttribute 
{ 
    // This method must be thread-safe since it is called by the thread-safe OnCacheAuthorization() method. 
    protected override bool AuthorizeCore(HttpContextBase httpContext) 
    { 
     if (base.AuthorizeCore(httpContext) && MyCustomAuthorizationHolds) 
      return true; 

     return false; 
    } 
} 
Cuestiones relacionadas