2012-04-26 9 views
6

Ho un'interfaccia utente con Jquery che effettua una chiamata a MVC utilizzando la richiesta Ajax.Attributo di autorizzazione personalizzata MVC per convalidare la richiesta

Vorrei convalidare ogni richiesta con il profilo utente (classe personalizzata che contiene numero account, ID ecc.).

Qualcuno potrebbe suggerire se è possibile creare un Attributo di autorizzazione personalizzato per verificare che sia la richiesta sia il profilo utente siano uguali?

Vorrei poi fare qualcosa di simile di seguito:

[AuthorizeUser] 
public ActionResult GetMyConsumption(string accountNumber) 
{ 
    ..... 
    return View(); 
} 
+0

Se siete disposti a analizzare i dati dal modulo di richiesta/querystring e convalidarli allora potrebbe essere possibile. Avrai pieno accesso a httpContext nel tuo attributo di autorizzazione personalizzato. Dovresti assumere che una variabile "accountNumber" deve esistere nel Form se un POST o QueryString se un GET. Il binding dei parametri (mappatura dei dati nella richiesta ai parametri nella tua azione) avverrà attorno al metodo OnActionExecuting che è post-Authorize. –

+0

Sì, verrà passato l'ID account. –

+1

Controlla http://stackoverflow.com/questions/6860686/extend-authorizeattribute-override-authorizecore-or-onauthorization (AuthorizeCore vs OnAuthorize) e qui c'è qualcuno che sta esaminando alcuni dati di richiesta (budget) per alcuni dati per determinare se l'utente è autorizzato o meno: http://stackoverflow.com/questions/5989100/asp-net-mvc-3-custom-authorisation –

risposta

17

si potrebbe scrivere autorizzare un attributo personalizzato:

public class AuthorizeUserAttribute : AuthorizeAttribute 
{ 
    protected override bool AuthorizeCore(HttpContextBase httpContext) 
    { 
     var isAuthorized = base.AuthorizeCore(httpContext); 
     if (!isAuthorized) 
     { 
      // The user is not authorized => no need to continue 
      return false; 
     } 

     // At this stage we know that the user is authorized => we can fetch 
     // the username 
     string username = httpContext.User.Identity.Name; 

     // Now let's fetch the account number from the request 
     string account = httpContext.Request["accountNumber"]; 

     // All that's left is to verify if the current user is the owner 
     // of the account 
     return IsAccountOwner(username, account); 
    } 

    private bool IsAccountOwner(string username, string account) 
    { 
     // TODO: query the backend to perform the necessary verifications 
     throw new NotImplementedException(); 
    } 
} 
+0

Grazie @Darin Dimitrov –

Problemi correlati