I have a project that I’ve built without using the default template, instead I did everything from beginning.
Now I need to implement checks for admin and I don’t think that
public ActionResult someAction()
{
if (session exists)
{
// do it
}
else
{
//redirect back or show 403
}
}
is a good idea on every delete/edit/create actions.
What I want to do instead is build action filter that will check if admin session exists and if there is no session it will redirect to 403 or something like that.
[AdminCheck]
public ActionResult someAction()
{
// do it
}
However I don’t know how to do that. I’ve did some research and put it up, but I have no idea how to implement functionality in it.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace stevePortfolio.Infrastructure
{
public class AdminCheck : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
base.OnActionExecuting(filterContext);
// No idea what to write here...
}
}
}
You should use the AuthorizeAttribute for this. You can use it out of the box to check if the user is a member of a specific role like this:
or you can Subclass it if you need more complexity and place in the required code.
You can then handle an unauthorized request any way you want. The example below does it by issuing a HTTP status code 403 and a jsonresult for my ajax methods to check, or for normal http requests, redirects to the “Not Authorized” page.