0

I am trying to integrate different techonologies(different domain each) and create RESTfull actions. For example i have an client (Apache cordova) and a server(.NET framework 4.6.1). In WebGet method all work fine, but in other methods doesnt. This is my test code for Login Action.

Javascript(angular)

    $http({
        method: 'Put',
        url: $rootScope.url + '/Login'
    }).then(function successCallback(response) {
    }, function errorCallback(response) {
    });

the variable $rootScope.url has the url that server is running.

C# MVC .NET

    [HttpPut]
    [AllowAnonymous]
    public async Task<ActionResult> Login()
    {
        try
        {
            var result = await SignInManager.PasswordSignInAsync("test3", "1!2@Qa", false, shouldLockout: false);
            return null;
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

When i make this call in network i get this

 http://localhost:4400/xhr_proxy?rurl=http%3A//localhost%3A49266/App//Login.

With some googling i get to result that Same-origin policy is the reason that this AJAX call fails.

Looking this article i get the reason why we should use the CORS. But i have not understand how is the perfect way to use them on production enviroment.

How can be sure that my server will accept calls only from my client? I have to add a custom header to client javascript calls, that the server will check if exist?

I found some solutions like HttpContext.Response.AppendHeader("Access-Control-Allow-Origin", "*");

or

   <httpProtocol>
  <customHeaders>
    <clear />
    <add name="Access-Control-Allow-Origin" value="*" />
  </customHeaders>
</httpProtocol>

But i think that using this way i will let any site with javascript to make actions to server.

How can create a secured cors policy?

GomuGomuNoRocket
  • 521
  • 1
  • 4
  • 27

1 Answers1

0

You are correct, using * will allow any site to use your API. You instead want to replace * with your fully qualified domain(s), for example https://www.{domain}.com. You can provide a comma separated list as well if you have multiple domains/subdomains.

Also, you can restrict the headers and methods as well if you have a specific set you are using. Here is some more info: https://docs.microsoft.com/en-us/aspnet/web-api/overview/security/enabling-cross-origin-requests-in-web-api

Kyle Dodge
  • 639
  • 4
  • 15