Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter actions based on UserAgent

Tags:

asp.net-mvc

Is there a simple way to apply a filter on action methods in ASP.NET MVC3 against specific types of UserAgents? I have a hacking network chewing on us in different ways. I can play cat and mouse with IPs, subnets, etc at the network/firewall level but would like to inject an app level assurance against things like Squid, etc as they appear to have certain patterns that arise. Not sure how this would affect performance but wondered if anyone has done this approach.

thanks in advance. doug

like image 861
dodegaard Avatar asked Jun 07 '26 04:06

dodegaard


1 Answers

You would have to create a custom action filter. Here is an example of one that returns an http 403 forbidden if the requesting user agent is a mozilla-based browser:

public class UserAgentActionFilterAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        if (filterContext.HttpContext.Request.UserAgent.ToLowerInvariant().Contains("mozilla"))
        {
            filterContext.Result = new HttpStatusCodeResult(403);
        }

        base.OnActionExecuting(filterContext);
    }
}

Just remember that user-agents can be faked if they realize that is how they are being blocked.

like image 99
doogle Avatar answered Jun 10 '26 19:06

doogle