How to secure a controller on WebAPI for use by only the local machine

前端 未结 2 1715
自闭症患者
自闭症患者 2021-01-01 17:11

I have an ASP.NET MVC website that makes use of WebAPI, SignalR.

I wish for my server (the same server that hosts the website) to make HTTP requests to a WebAPI cont

2条回答
  •  生来不讨喜
    2021-01-01 17:49

    If you ONLY wanted to accept requests that originated from the same machine, you could check the IsLocal property of the request context MSDN.

    HttpRequest.Context.Request.IsLocal
    

    You could then build it into a custom authorize attribute and register it globally, enforcing the requirement on all of your Web API controllers.

    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // Other Web API configuration code goes here
    
            // This is a globally registered attribute
            config.Filters.Add(new LocalRequestOnlyAttribute()); 
        }
    }
    
    public class LocalRequestOnlyAttribute : AuthorizeAttribute
    {
        protected override bool IsAuthorized(HttpActionContext context)
        {
            return context.RequestContext.IsLocal;
        }
    }
    

提交回复
热议问题