2016-04-05 10 views
0

Ich muss Digest-Authentifizierung mit ASP.NET MVC 3 implementieren. Zu diesem Zweck habe ich von AuthorizeAttribute und HttpUnauthorizedResult geerbt. Der Code lautet wie folgt:ExecuteResult-Methode nicht aufgerufen HttpUnauthorizedResult abgeleitete Klasse

[AttributeUsage (AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true, Inherited = true)] 
public class SessionAuthorize: AuthorizeAttribute { 
    public override void OnAuthorization (AuthorizationContext actionContext) { 
     try { 
      if (null != actionContext.HttpContext.Request.Headers["Authorization"]) 
       // authorization is on the way 
       // <...> 
      else 
       actionContext.Result = new HttpDigestUnauthorizedResult(); 
     } catch (Exception ex) { 
      Trace.TraceWarning ("SessionAuthorize.OnAuthorization failed: {0}", ex.Message); 
     } 
     base.OnAuthorization (actionContext); 
    } 
} 

public class HttpDigestUnauthorizedResult: HttpUnauthorizedResult { 
    public HttpDigestUnauthorizedResult() : base() { 
    } 
    public override void ExecuteResult (ControllerContext context) { 
     if (context == null) 
      throw new ArgumentNullException ("context"); 
     // this is supposed to initialize digest authentification exchange 
     context.HttpContext.Response.AddHeader ("WWW-Authenticate", string.Format ("Digest realm=\"somerealm\",qop=\"auth\",nonce=\"{0}\",opaque=\"{1}\""/*, <...>*/)); 
     base.ExecuteResult (context); 
    } 
} 

-Code für Controller/Aktion ist wie folgt:

public class DefaultController: Controller { 
    [SessionAuthorize] 
    public ViewResult Index() { 
     return View(); 
    } 
} 

so dass es nichts Besonderes tun.

Allerdings überschrieben ExecuteResult wird nie aufgerufen, und nur Standard 401-Seite zurückgegeben wird. Was fehlt mir hier? Woher soll ExecuteResult genannt werden?

Antwort

2

das richtige Muster ist: verwenden AuthorizeCore (a bool dass Rückkehr) zu erklären, wenn die aktuelle Anforderung autorisiert ist oder nicht, und diejenigen in unberechtigte Zugriffe HandleUnauthorizedRequest Verfahren zu behandeln. Es ist falsch, alles in OnAuthorization zu setzen, denn nach the source code wird unter bestimmten Umständen OnCacheAuthorization Methode anstelle von OnAuthorization aufgerufen.

protected override bool AuthorizeCore(HttpContextBase httpContext) 
{ 
    if (httpContext.Request.Headers["Authorization"] == null) 
    { 
     return false; 
    } 

    return base.AuthorizeCore(httpContext); 
} 

protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext) 
{ 
    filterContext.Result = new HttpDigestUnauthorizedResult(); 
} 
+0

Danke, das war genau, wo das Problem war. –