Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Allow only requests from local machine in WebAPI 2

There are some action methods in my WebAPI 2 application where I would like to disable remote accessibility (scheduled administrative tasks). Other action methods should be publicly available. Is an ActionFilter the best bet in this case?

like image 525
Mike Cole Avatar asked Dec 23 '13 18:12

Mike Cole


People also ask

How do you restrict requests so they only work if it is accessed by a specific domain?

The RestrictDomain filter will do exactly that. It will restrict every request whose host is not in the AllowedHosts . So if I include "example.com" in the constructor of RestrictDomain , then every requests that doesn't come from example.com will result in a failed HTTP response.

What are the differences between Web API and Web API 2?

Actually WebAPI 2.0 is enhanced feature of WebApi there is no difference between this two. In version 2.0, the Web API framework has been enhanced to support the following features: IHttpActionResult return type. A new Routing Attribute.

How do we limit access to methods with an HTTP verb in Web API?

We can do it by defining HTTP verbs as an attribute to restrict access. For example, [HttpPost] public void Method1(Class obj)

How do I enable cross origin requests in Web API?

To send credentials with a cross-origin request, the client must set XMLHttpRequest. withCredentials to true. If this property is true, the HTTP response will include an Access-Control-Allow-Credentials header. This header tells the browser that the server allows credentials for a cross-origin request.


1 Answers

I think that cross-origin resource sharing (CORS) will help your if you have local url for your site. You can apply list of origins for public actions and only local origin for your secured actions. For example:

Local:

[EnableCors(Origins = new[] { "http://localhost", "http://sample.com" })]
public class ValuesController : ApiController
{
......
}

and secured:

[EnableCors(origins: "http://localhost")]
public class ValuesController : ApiController
{
......
}

You can find out more details by the next links: CORS support for ASP.NET Web API and Scope Rules for [EnableCors]

like image 173
RredCat Avatar answered Oct 06 '22 00:10

RredCat