zhuber
zhuber

Reputation: 5534

Check if API controller method has authorize attribute

I'm trying to determine whether API method has authorize attribute and although I can easily find that using MethodInfo, I can't seem to find a way to handle check when Authorize is set on controller level.

Basically I need to know if either controller or method has Authorize attribute.

public class SecurityRequirementsOperationFilter : IOperationFilter
{
    public void Apply(Operation operation, OperationFilterContext context)
    {
        var hasAuthorizeAttribute = context.MethodInfo
            .GetCustomAttributes(true)
            .OfType<AuthorizeAttribute>()
            .Any();

        if (!hasAuthorizeAttribute)
        {   
            operation.Security = new List<IDictionary<string, IEnumerable<string>>>();
        }
    }
}

Upvotes: 2

Views: 1976

Answers (1)

zhuber
zhuber

Reputation: 5534

I've managed to find a way to find if method has either controller or method Authorize attribute.

var hasAuthAttribute = context.MethodInfo.DeclaringType.GetCustomAttributes(true)
            .Union(context.MethodInfo.GetCustomAttributes(true))
            .OfType<AuthorizeAttribute>()
            .Any();

Upvotes: 4

Related Questions