I. Kapri
I. Kapri

Reputation: 76

Is it possible to create a custom MyAuthorizeAttribute by inheriting (if possible) from the AuthorizeAttribute in .NET Core?

Is it possible to create a custom AuthorizeAttribute as follows ?

[...]
public class MyAuthorizeAttribute : AuthorizeAttribute, ... {
    // Code (overridings e. g.) goes here...
}

Thank you for your infos!

Upvotes: 0

Views: 124

Answers (1)

Panagiotis Kanavos
Panagiotis Kanavos

Reputation: 131728

This is already supported. You have to do more than create a custom attribute though. An attribute only stores some information in the generated binary, it doesn't actually affect how an application behaves. It's the application itself that inspects attributes and their values and modifies its behavior.

In this case, the code that authorizes calls is ASP.NET Core Identity. Identity reads the role, claims or policy values stored in AuthorizationAttribute and passes them to its default authorization provider. To customize authorization, one has to create a custom authorization provider, not just a custom attribute.

In the documentation's example, the custom attribute modifies the Policy value used by ASP.NET Identity based on the Age property :

internal class MinimumAgeAuthorizeAttribute : AuthorizeAttribute
{
    const string POLICY_PREFIX = "MinimumAge";

    public MinimumAgeAuthorizeAttribute(int age) => Age = age;

    // Get or set the Age property by manipulating the underlying Policy property
    public int Age
    {
        get
        {
            if (int.TryParse(Policy.Substring(POLICY_PREFIX.Length), out var age))
            {
                return age;
            }
            return default(int);
        }
        set
        {
            Policy = $"{POLICY_PREFIX}{value.ToString()}";
        }
    }
}

The custom authorization provider uses that value to authorize a call only if it fulfills its policy:

internal class MinimumAgePolicyProvider : IAuthorizationPolicyProvider
{
    const string POLICY_PREFIX = "MinimumAge";

    // Policies are looked up by string name, so expect 'parameters' (like age)
    // to be embedded in the policy names. This is abstracted away from developers
    // by the more strongly-typed attributes derived from AuthorizeAttribute
    // (like [MinimumAgeAuthorize()] in this sample)
    public Task<AuthorizationPolicy> GetPolicyAsync(string policyName)
    {
        if (policyName.StartsWith(POLICY_PREFIX, StringComparison.OrdinalIgnoreCase) &&
            int.TryParse(policyName.Substring(POLICY_PREFIX.Length), out var age))
        {
            var policy = new AuthorizationPolicyBuilder(CookieAuthenticationDefaults.AuthenticationScheme);
            policy.AddRequirements(new MinimumAgeRequirement(age));
            return Task.FromResult(policy.Build());
        }

        return Task.FromResult<AuthorizationPolicy>(null);
    }
}

Upvotes: 2

Related Questions