protected virtual void UnauthorizedResponse(Operation operation, OperationFilterContext context)
        {
            var allowsAnonymous = ActionAttributes.OfType <AllowAnonymousAttribute>().Any();

            if (operation.Responses.ContainsKey("401"))
            {
                if (allowsAnonymous)
                {
                    operation.Responses.Remove("401");
                }
                else
                {
                    operation.Responses["401"].Description = "Unauthorized";
                }
                return;
            }
            ;

            if (!CombinedAttributes.OfType <AuthorizeAttribute>().Any() || allowsAnonymous)
            {
                return;
            }
            operation.Responses.Add("401", new Response
            {
                Description = "Unauthorized",
                Schema      = context.SchemaRegistry.GetOrRegister(typeof(Error.Error))
            });
        }
        private static IEnumerable <ActionInfo> GetAttributeRoutedActions(
            ActionAttributes actionAttributes,
            string actionName)
        {
            var actions = new List <ActionInfo>();

            // This is the case where the controller has [Route] applied to it and
            // the action doesn't have any [Route] or [Http*] attribute applied.
            if (!actionAttributes.RouteTemplateProviderAttributes.Any())
            {
                actions.Add(new ActionInfo
                {
                    ActionName             = actionName,
                    HttpMethods            = null,
                    RequireActionNameMatch = true,
                    AttributeRoute         = null
                });
            }

            foreach (var routeTemplateProvider in actionAttributes.RouteTemplateProviderAttributes)
            {
                actions.Add(new ActionInfo()
                {
                    ActionName             = actionName,
                    HttpMethods            = GetRouteTemplateHttpMethods(routeTemplateProvider),
                    RequireActionNameMatch = true,
                    AttributeRoute         = routeTemplateProvider
                });
            }

            return(actions);
        }
        /// <summary>
        /// Returns `[{actionAttributes}]{ActionName}`
        /// </summary>
        public override string ToString()
        {
            const string attribute        = "Attribute";
            var          actionAttributes = string.Join(",", ActionAttributes.Select(a => a.GetType().Name.Replace(attribute, "")));

            return($"[{actionAttributes}]{ActionName}");
        }
Esempio n. 4
0
 public virtual void Apply(Operation operation, OperationFilterContext context)
 {
     ActionAttributes     = context.ApiDescription.GetActionAttributes().OfType <Attribute>();
     ControllerAttributes = context.ApiDescription.GetControllerAttributes().OfType <Attribute>();
     CombinedAttributes   = ActionAttributes.Union(ControllerAttributes);
     ConfigureResponses(operation, context);
 }
Esempio n. 5
0
        private static IEnumerable <ActionInfo> GetHttpConstrainedActions(
            ActionAttributes actionAttributes,
            string actionName)
        {
            var httpMethodProviders = actionAttributes.HttpMethodProviderAttributes;
            var httpMethods         = httpMethodProviders.SelectMany(x => x.HttpMethods).Distinct().ToArray();

            if (httpMethods.Length > 0)
            {
                foreach (var httpMethod in httpMethods)
                {
                    yield return(new ActionInfo()
                    {
                        HttpMethods = new string[] { httpMethod },
                        ActionName = actionName,
                        Attributes = actionAttributes.Attributes,
                        RequireActionNameMatch = true,
                    });
                }
            }
            else
            {
                yield return(new ActionInfo()
                {
                    HttpMethods = httpMethods,
                    ActionName = actionName,
                    Attributes = actionAttributes.Attributes,
                    RequireActionNameMatch = true,
                });
            }
        }
Esempio n. 6
0
        private IEnumerable <ActionInfo> GetActionsForMethodsWithCustomAttributes(
            ActionAttributes actionAttributes,
            MethodInfo methodInfo,
            TypeInfo controller)
        {
            var hasControllerAttributeRoutes = HasValidControllerRouteTemplates(controller);

            // We need to check controllerRouteTemplates to take into account the
            // case where the controller has [Route] on it and the action does not have any
            // attributes applied to it.
            if (actionAttributes.HasSpecialAttribute() || hasControllerAttributeRoutes)
            {
                var actionNameAttribute = actionAttributes.ActionNameAttribute;
                var actionName          = actionNameAttribute != null ? actionNameAttribute.Name : methodInfo.Name;

                // The moment we see a non null attribute route template in the method or
                // in the controller we consider the whole group to be attribute routed actions.
                // If a combination ends up producing a non attribute routed action we consider
                // that an error and throw at a later point in the pipeline.
                if (hasControllerAttributeRoutes || ActionHasAttributeRoutes(actionAttributes))
                {
                    return(GetAttributeRoutedActions(actionAttributes, actionName));
                }
                else
                {
                    return(GetHttpConstrainedActions(actionAttributes, actionName));
                }
            }
            else
            {
                // If the action is not decorated with any of the attributes,
                // it would be handled by convention.
                return(Enumerable.Empty <ActionInfo>());
            }
        }
Esempio n. 7
0
 public void Apply(OpenApiOperation operation, OperationFilterContext context)
 {
     ActionAttributes     = context.MethodInfo.GetCustomAttributes(true).OfType <Attribute>();
     ControllerAttributes = context.MethodInfo.DeclaringType.GetCustomAttributes(true).OfType <Attribute>();
     CombinedAttributes   = ActionAttributes.Union(ControllerAttributes);
     ConfigureResponses(operation, context);
     ExcludeSwaggerResonse(operation);
 }
 public void Apply(Operation operation, Swashbuckle.AspNetCore.SwaggerGen.OperationFilterContext context)
 {
     ActionAttributes     = context.ApiDescription.ActionAttributes().OfType <Attribute>();
     ControllerAttributes = context.ApiDescription.ActionAttributes().OfType <Attribute>();
     CombinedAttributes   = ActionAttributes.Union(ControllerAttributes);
     ConfigureResponses(operation, context);
     ExcludeSwaggerResonse(operation);
 }
 private static bool ActionHasAttributeRoutes(ActionAttributes actionAttributes)
 {
     // We neet to check for null as some attributes implement IActionHttpMethodProvider
     // and IRouteTemplateProvider and allow the user to provide a null template. An example
     // of this is HttpGetAttribute. If the user provides a template, the attribute marks the
     // action as attribute routed, but in other case, the attribute only adds a constraint
     // that allows the action to be called with the GET HTTP method.
     return(actionAttributes.RouteTemplateProviderAttributes
            .Any(rtp => rtp.Template != null));
 }
Esempio n. 10
0
        public void WhenSetNullableIntIsCalledWitNullThenValueIsNotInDictionary()
        {
            ActionAttributes attributes = new ActionAttributes();

            string memberName = "_name";

            attributes.SetNullableInt(memberName, null);

            IReadOnlyDictionary <string, string> data = attributes.Data;

            Assert.AreEqual(0, data.Count);
        }
        private static IEnumerable <ActionInfo> GetHttpConstrainedActions(
            ActionAttributes actionAttributes,
            string actionName)
        {
            var httpMethodProviders = actionAttributes.HttpMethodProviderAttributes;
            var httpMethods         = httpMethodProviders.SelectMany(x => x.HttpMethods).Distinct().ToArray();

            yield return(new ActionInfo()
            {
                HttpMethods = httpMethods,
                ActionName = actionName,
                RequireActionNameMatch = true,
            });
        }
Esempio n. 12
0
        public void WhenSetNullableIntIsCalledWithNotNullThenValueIsInDictionary()
        {
            ActionAttributes attributes = new ActionAttributes();

            string memberName  = "_name";
            int    memberValue = 7;

            attributes.SetNullableInt(memberName, memberValue);

            string key = "name";
            IReadOnlyDictionary <string, string> data = attributes.Data;

            Assert.AreEqual(1, data.Count);
            Assert.IsTrue(data.ContainsKey(key));
            Assert.AreEqual(memberValue.ToString(), data[key]);
        }
Esempio n. 13
0
        public void WhenSetStringIsCalledThenValueIsInDictionary()
        {
            ActionAttributes attributes = new ActionAttributes();

            string memberName  = "_name";
            string memberValue = "value";

            attributes.SetString(memberName, memberValue);

            string key = "name";
            IReadOnlyDictionary <string, string> data = attributes.Data;

            Assert.AreEqual(1, data.Count);
            Assert.IsTrue(data.ContainsKey(key));
            Assert.AreEqual(memberValue, data[key]);
        }
Esempio n. 14
0
        private static IEnumerable <ActionInfo> GetAttributeRoutedActions(
            ActionAttributes actionAttributes,
            string actionName)
        {
            var actions = new List <ActionInfo>();

            // This is the case where the controller has [Route] applied to it and
            // the action doesn't have any [Route] or [Http*] attribute applied.
            if (!actionAttributes.RouteTemplateProviderAttributes.Any())
            {
                actions.Add(new ActionInfo
                {
                    Attributes             = actionAttributes.Attributes,
                    ActionName             = actionName,
                    HttpMethods            = null,
                    RequireActionNameMatch = true,
                    AttributeRoute         = null
                });
            }

            foreach (var routeTemplateProvider in actionAttributes.RouteTemplateProviderAttributes)
            {
                // We want to exclude the attributes from the other route template providers;
                var attributes = actionAttributes.Attributes
                                 .Where(a => a == routeTemplateProvider || !(a is IRouteTemplateProvider))
                                 .ToArray();

                actions.Add(new ActionInfo()
                {
                    Attributes             = attributes,
                    ActionName             = actionName,
                    HttpMethods            = GetRouteTemplateHttpMethods(routeTemplateProvider),
                    RequireActionNameMatch = true,
                    AttributeRoute         = routeTemplateProvider
                });
            }

            return(actions);
        }
Esempio n. 15
0
    private static void DemoFlags()
    {
        Console.WriteLine("\n\nDemo start: Demo of enumerated flags types.");
        ActionAttributes aa = ActionAttributes.Read
                              | ActionAttributes.Write | ActionAttributes.Query;

        // What type is this enum & what is it derived from
        Console.WriteLine("   The " + aa.GetType() + " type is derived from " + aa.GetType().BaseType);

        // What is the underlying type used for the Enum's value
        Console.WriteLine("   Underlying type: " + Enum.GetUnderlyingType(aa.GetType()));

        // Display the set of legal enum values
        ActionAttributes[] o = (ActionAttributes[])Enum.GetValues(aa.GetType());
        Console.WriteLine("\n   Number of valid enum values: " + o.Length);
        for (int x = 0; x < o.Length; x++)
        {
            ActionAttributes aax = ((ActionAttributes)(o[x]));
            Console.WriteLine("   {0}: Name={1,10}\tNumber={2}", x,
                              aax.ToString("G"), ((ActionAttributes)aax).ToString("D"));
        }

        // Check if a value is legal for this enum
        Console.WriteLine("\n   8 is a valid enum value: " + Enum.IsDefined(aa.GetType(), 8));   // True
        Console.WriteLine("   6 is a valid enum value: " + Enum.IsDefined(aa.GetType(), 6));     // False

        // Display the enum's value as a string
        Console.WriteLine("\n   aa's value as a string: " + aa.ToString("G"));   // Read|Write|Query
        Console.WriteLine("   aa's value as a number: " + aa.ToString("D"));     // 11

        // Convert a string to an enum's value
        aa  = (ActionAttributes)(Enum.Parse(typeof(ActionAttributes), "Write"));
        aa |= (ActionAttributes)(Enum.Parse(typeof(ActionAttributes), "Sync"));
        Console.WriteLine("\n   aa's value as a string: " + aa.ToString("G"));   // Write|Sync
        Console.WriteLine("   aa's value as a number: " + aa.ToString("D"));     // 18

        Console.WriteLine("Demo stop: Demo of enumerated flags types.");
    }
Esempio n. 16
0
        public void WhenSetNullableIntIsCalledWitMultipleValuesThenAllValuesAreInDictionary()
        {
            ActionAttributes attributes = new ActionAttributes();

            string memberName1  = "_name1";
            string memberValue1 = "value1";

            attributes.SetString(memberName1, memberValue1);

            string memberName2  = "_name2";
            int    memberValue2 = 7;

            attributes.SetInt(memberName2, memberValue2);

            string key1 = "name1";
            string key2 = "name2";
            IReadOnlyDictionary <string, string> data = attributes.Data;

            Assert.AreEqual(2, data.Count);
            Assert.IsTrue(data.ContainsKey(key1));
            Assert.AreEqual(memberValue1, data[key1]);
            Assert.IsTrue(data.ContainsKey(key2));
            Assert.AreEqual(memberValue2.ToString(), data[key2]);
        }