Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
297 views
in Technique[技术] by (71.8m points)

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

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 controller - I wish to do this so that I can hook into my website's SignalR functionality.

I want to make it so that the websites users can't access the methods on the WebAPI controller, but the server can.

I have looked at the options for securing WebAPI requests generally and it seems like I have the following options available to me:

  • Send a username and password over each request AKA Basic Authentication
  • Generate a "Client Certificate" and send that with each request

These are the only two methods that sound like they would work, but I wonder if it's overkill to use these methods if the requests are going to originate from localhost (the same server).

Is it overkill, is there an easier way to restrict HTTP requests from the local machine to a WebAPI controller?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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;
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...