DucDigital
DucDigital

Reputation: 4622

Custom Authorize Attribute additional Param?

im looking for a way to customize my Authorize Attribute so that i can implement it correctly with my own MembershipProvider.

What i need is to have the IsInRoles(string role, int perm) for example, in other word, i want to have it replace with a new IsinRoles or maybe create another method to archive this result.

Is it possible? or i need to write a different authorize attribute?

Thank you very much for your concern...

PS: im working on ASP.net MVC, so i need to have the [Authorize] filter up and running.

Upvotes: 1

Views: 3930

Answers (1)

Kelsey
Kelsey

Reputation: 47776

I think you can just add a public property to your custom AuthorizeAttribute.

public class CustomAuthorizeAttribute : AuthorizeAttribute
{
    /// <summary>
    /// Add the allowed roles to this property.
    /// </summary>
    public YourCustomRoles RequiredRole;

    public int YourCustomValue;

    /// <summary>
    /// Checks to see if the user is authenticated and has the
    /// correct role to access a particular view.
    /// </summary>        
    /// <param name="httpContext"></param>
    /// <returns></returns>
    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        if (httpContext == null) throw new ArgumentNullException("httpContext");

        // Make sure the user is authenticated.
        if (httpContext.User.Identity.IsAuthenticated == false) return false;

        // Can use your properties if needed and do your checks
        bool authorized = DoSomeCustomChecksHere();

        return authorized;
    }
}

Usage I think would be (haven't tried it though):

[CustomAuthorizeAttribute (RequiredRole=MyCustomRole.Role1 | MyCustomRole.Role2, YourCustomValue=1234)]

Upvotes: 7

Related Questions