2

I have a web API controller in asp.net core version 2.
this controller must receive requests from one domain for example test.com
test.com 's IP always change, therefor i can't limit this controller to IP.
what method can i use ?
just one of the controllers and the other's allow's any origins.
the controller is like this :

    [HttpPost]
    public IActionResult CBack([RequiredFromQuery]string id,
                               [FromBody] Newtonsoft.Json.Linq.JObject Cypher)

1 Answer 1

1

You can use scoped Cross-Origin Requests (CORS):

[EnableCors("YourPolicy")]
[HttpPost]
public IActionResult CBack([RequiredFromQuery]string id,
                           [FromBody] Newtonsoft.Json.Linq.JObject Cypher)

This allows you to enable Cross-Origin Requests per controller or action.

Don't forget to add the CORS service in your Startup.cs file. You must also register a custom policy first.

// ConfigureServices
services.AddCors(options =>
{
    options.AddPolicy("YourPolicy",
        builder => builder.WithOrigins("http://example.com"));
});
Sign up to request clarification or add additional context in comments.

4 Comments

Please NOTE that CORS is only for Ajax (JavaScript) calls from within a browser!!! Directly posting to the actions (i.e. via a Java/C#/C++/Swift Rest client or HttpClients) will NOT be affected by CORS. If you really want to implement access control, you should use something like a filter and inspect the Request.Host property from there. Not sure how reliable that is though
Also as additional note, in ASP.NET Core 2.2 introduces Dispatch Routing which may be more useful then the current MVC routing, as it makes the route available very early in the pipeline, allowing to do such checks in the middleware level (right now, the route is not know until the MVC middleware is called, which is to late to do any kind of effective blocking except for action/controller based middleware or using filters)
@Tseng there is any way of check Request.Host without checking in every controller? I want all the site only be acceptable from my domain
@Leandro I think your best bet would be to configure this in your web server configuration (Nginx / Apache). Not sure if this is best-practice, but it prevents access from everywhere, except the addresses you allow.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.