¿Cómo creo un atributo personalizado para extender el atributo Authorize existente en MVC?asp.net mvc Agregar al atributo AUTORIZAR
Respuesta
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 */);
}
bien, pero ¿cómo puedo redireccionar correctamente a la última página? – zsharp
¿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. –
@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
public class CoolAuthorizeAttribute : AuthorizeAttribute
{
}
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>
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;
}
}
- 1. ASP.NET MVC redirige del atributo
- 2. Asp.net MVC OutputCache atributo y expiración
- 3. Autorizar el atributo en ASP.NET MVC
- 4. ASP.Net MVC 3: Atributo Autorizar Inverso
- 5. Anular Autorizar atributo en ASP.NET MVC
- 6. MVC ASP.NET MVC3 AllowHtml ¿Atributo no funciona?
- 7. Atributo personalizado escrito en C# ASP.Net MVC como Autorizar atributo
- 8. ASP.Net MVC 3 - ¿El atributo del orden en el atributo HandleError parece funcionar al revés?
- 9. ASP.NET MVC Agregar registros secundarios dinámicamente
- 10. ¿Cómo agregar un atributo al nodo Nokogiri?
- 11. Agregar atributos personalizados al control asp.NET RadioButton
- 12. ASP.NET MVC - ¿Agregar querystring "length =" a ActionLinks?
- 13. asp.net mvc agregar css a editorfor?
- 14. ASP.NET MVC agregar clase css a actionlink
- 15. Agregar encabezados en ASP.NET MVC 3
- 16. Agregar condicionalmente htmlAttributes a ASP.NET MVC Html.ActionLink
- 17. ASP.NET MVC - pasar parámetros al controlador
- 18. Error al manejar en ASP.NET MVC
- 19. Autenticación de formularios MVC de ASP.NET + Autorizar atributo + Roles simples
- 20. Autorizar el atributo y jquery AJAX en asp.net MVC
- 21. ASP.NET MVC: AJAX ActionLink: segmentar un atributo HTML
- 22. Minificar atributo de filtro de acción en ASP.NET MVC
- 23. Html.TextBox atributo condicional con ASP.NET MVC Vista previa 5
- 24. Validación del modelo/ASP.NET MVC 3 - Atributo requerido condicional
- 25. ASP.NET MVC 2 y ComponentModel.DataAnnotations Validación: atributo de valor mínimo
- 26. ValidateInput atributo no parecen funcionar en ASP.NET MVC
- 27. ¿Qué hace el atributo EnumDataType en ASP.NET MVC?
- 28. ASP.NET MVC: Problema al establecer el atributo Autorizar Rol de una variable, requiere const
- 29. ASP.NET MVC atributo sólo para permitir al usuario editar su/su propio contenido
- 30. Problema al configurar un atributo html que contiene guiones en ASP.NET MVC
Por favor, agregue más detalles, ¿qué es exactamente lo que quiere extender? –
por ahora solo quiero poder redireccionar a la página correcta en lugar de a la página de inicio predeterminada. – zsharp
Puede actualizar su pregunta para que todos puedan saber lo que necesita. –