I want to have a filter on my custom authorize attribute but I don't have idea how to add it in my code. I want it like this.
[CustomAuthorize(Roles="Admin, Supervisor, SystemUser")]
[CustomAuthorize(Users="Kenneth,John")]
[CustomAuthorize(Customfilter="Update, View")]
This is my customauthorize, what to add in my code to have a filter?
public class CustomAuthorizeAttribute : AuthorizeAttribute
{
ApplicationDbContext _context = new ApplicationDbContext(); // my entity
public override void OnAuthorization(HttpActionContext actionContext)
{
if (AuthorizeRequest(actionContext))
{
return;
}
HandleUnauthorizedRequest(actionContext);
}
protected override void HandleUnauthorizedRequest(HttpActionContext actionContext)
{
if (((System.Web.HttpContext.Current.User).Identity).IsAuthenticated)
{
actionContext.Response = new HttpResponseMessage()
{
StatusCode = HttpStatusCode.Unauthorized,
Content = new StringContent("You are unauthorized to access this resource")
};
}
else
{
base.HandleUnauthorizedRequest(actionContext);
}
}
private bool AuthorizeRequest(HttpActionContext actionContext)
{
var user = _context.Users.ToList();
if (user != null)
return true;
else
return false;
}
}
答案 0 :(得分:0)
您可以使用下面的惯例化
public class CustomAuthorize : System.Web.Http.AuthorizeAttribute
{
private string Roles { get; set; }
private string Customfilter { get; set; }
private string Users { get; set; }
public CustomAuthorize(string roles, string users,string Customfilter)
{
Roles = roles;
Users = users;
Customfilter = Customfilter
}
//Your default code here
ApplicationDbContext _context = new ApplicationDbContext(); // my entity
public override void OnAuthorization(HttpActionContext actionContext)
{
if (AuthorizeRequest(actionContext))
{
return;
}
HandleUnauthorizedRequest(actionContext);
}
protected override void HandleUnauthorizedRequest(HttpActionContext actionContext)
{
if (((System.Web.HttpContext.Current.User).Identity).IsAuthenticated)
{
actionContext.Response = new HttpResponseMessage()
{
StatusCode = HttpStatusCode.Unauthorized,
Content = new StringContent("You are unauthorized to access this resource")
};
}
else
{
base.HandleUnauthorizedRequest(actionContext);
}
}
private bool AuthorizeRequest(HttpActionContext actionContext)
{
var user = _context.Users.ToList();
if (user != null)
return true;
else
return false;
}
}