ho potuto fare questo con un attributo personalizzato come segue.
[AuthorizeUser(AccessLevel = "Create")]
public ActionResult CreateNewInvoice()
{
//...
return View();
}
Classi di attributi personalizzati come segue.
public class AuthorizeUserAttribute : AuthorizeAttribute
{
// Custom property
public string AccessLevel { get; set; }
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
var isAuthorized = base.AuthorizeCore(httpContext);
if (!isAuthorized)
{
return false;
}
string privilegeLevels = string.Join("", GetUserRights(httpContext.User.Identity.Name.ToString())); // Call another method to get rights of the user from DB
return privilegeLevels.Contains(this.AccessLevel);
}
}
È possibile reindirizzare un utente non autorizzato nella vostra abitudine AuthorisationAttribute
sovrascrivendo il metodo HandleUnauthorizedRequest
:
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
filterContext.Result = new RedirectToRouteResult(
new RouteValueDictionary(
new
{
controller = "Error",
action = "Unauthorised"
})
);
}
Ho provato il tuo esempio di HandleUnauthorizedRequest ma quando ho specificare il RouteValueDictionary, reindirizza solo per io un percorso che non esiste. Si aggiunge il percorso che voglio reindirizzare l'utente a al percorso che l'utente ha voluto l'accesso ... si ottengo qualcosa di simile: localhost: 9999/admin/casa quando volevo localhost: 9999/Casa – Marin
@Marin Prova ad aggiungere area = string.Empty in RouteValueDictionary – Alex
Stavo facendo l'upvoting ma poi ho visto "if (condition) {return true;} else {return false;}" alla fine .... – GabrielBB