Angled POST with customized header and CORS

8

I need to perform a POST request using angular (http.post) and I need to pass my access credentials (I am using basic authentication) to my API (.NET) in my header.

  

Authorization : Basic dXNlcm5hbWU6cGFzc3dvcmQ =

No angular change the header as I need it

$http.defaults.headers.common.Authorization = 'Basic ' + credentials;

But when I do POST to the API, the Angle (or browser) changes my POST to OPTIONS

  

Request Method : OPTIONS

I have already looked in various places about it, but I could not find a solution. In the Web.Config of my API I have already set up to allow CORS.

  <customHeaders>
    <add name="Access-Control-Allow-Origin" value="http://localhost:9000" />
    <add name="Access-Control-Allow-Headers" value="Origin, X-Requested-With, Content-Type, Accept, Cache-Control" />
    <add name="Access-Control-Allow-Credentials" value="true" />
    <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
  </customHeaders>

Can anyone tell me what I might be doing wrong? How to look for the solution? Thanks in advance!

    
asked by anonymous 26.10.2015 / 18:17

2 answers

6

Problem solved, really the problem was in my WebApi.

  

To add CORS support I had to use the package    Microsoft.AspNet.WebApi.Cors from NuGet, following the article I found here .

Add the Microsoft.AspNet.WebApi.Cors package to the project using NuGet

Install-Package Microsoft.AspNet.WebApi.Cors

Add the code in the WebApiConfig.cs

public static void Register(HttpConfiguration config)
{
    // New code
    config.EnableCors();
}

To enable cross-origin add [EnableCors] to the controller or method you want

[EnableCors(origins: "http://example.com", headers: "*", methods: "*")]
public class TestController : ApiController
{
    // Controller methods not shown...
}

If you want to enable globally

public static void Register(HttpConfiguration config)
{
    var corsAttr = new EnableCorsAttribute("http://example.com", "*", "*");
    config.EnableCors(corsAttr);
}
    
29.10.2015 / 18:56
3

You need to add the resource URL to the DelegateProvider whitelist . So:

myApp
.config(['$sceDelegateProvider', function($sceDelegateProvider) {
     $sceDelegateProvider.resourceUrlWhitelist(['self','http://localhost:9000/**']);
 }]);

If you do not specify, your browser will attempt to obtain the server authorization list, via OPTIONS header. This is part of the CORS specification.

    
26.10.2015 / 20:11