3

I am implementing a Custom Authorize Attribute in MVC3. I am storing page level permissions in the database, and would like to pass my authorize attribute a Page ID. Something of the sort:

[CustomAuthorize(PageID = 1)]
public ActionResult About()
{
    return View();
}

How do I implement the Authorize Attribute, as the AuthorizeCore only takes one argument in the override?

public class CustomAuthorizeAttribute : AuthorizeAttribute
{
    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
    }
}

2 Answers 2

5

You would define a class-level variable to hold the PageID, and your attribute's constructor would take that as an argument. Or to use it like you have in your example, you would create a public property called PageID.

public class CustomAuthorizeAttribute : AuthorizeAttribute
{
    public int PageID{get; set;}

    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
         //use PageID to do checks here.
    }
}

Then within your AuthorizeCore, you would use that property/field value to do your checks.

Sign up to request clarification or add additional context in comments.

Comments

0

(Custom User Type ) Just some tweaking

Test Controller

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;


namespace Authorise.Controllers
{
    public class TestController : Controller
    {
        // GET: /Default1/
        [CustomAuthorize(UserType = "Admin")]
        public ActionResult Index()
        {
            return View();
        }

    }

    public class CustomAuthorizeAttribute : AuthorizeAttribute
    {
        public string UserType { get; set; }

        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            if (UserType == "Admin")
            {
                return true;
            }
            else
            {
                return false;
            }
        }
    }
}

Test View

@{
    ViewBag.Title = "Test";
}

<h2>Test</h2>

Account Controller

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace Authorise.Controllers
{
    public class AccountController : Controller
    {
        //
        // GET: /Account/

        public ActionResult Index()
        {
            return View();
        }
        public ActionResult LogOn()
        {
            return View();
        }

    }
}

Account Logon View

@{
   ViewBag.Title = "LogOn";
}

LogOn

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.