Подтвердить что ты не робот

Asp.net mvc Добавление в атрибут AUTHORIZE

Как создать пользовательский атрибут для расширения существующего атрибута Authorize в MVC?

4b9b3361

Ответ 1

Выведите свой класс из AuthorizeAttribute. Переопределите метод OnAuthorization. Добавьте и настройте 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 */);
 }

Ответ 2

Вам не нужно расширять этот атрибут, достаточно web.config. Пожалуйста, прочитайте формы Элемент для аутентификации. Обратите внимание на defaultUrl. Это то, что вам нужно.

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

Ответ 3

public class CoolAuthorizeAttribute :  AuthorizeAttribute
{
}

Ответ 4

Я предлагаю, если вы просто хотите расширить текущий атрибут AuthorizeAttribute и добавить к нему свою собственную авторизацию, вместо того, чтобы переопределять OnAuthorization, просто переопределите AuthorizeCore и добавьте к нему состояние MyCustomAuthorizationHolds.

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;
    }
}