0

I am building a SPA application using Angular JS and the backend is asp.net WebAPI using bearer tokens. I have an interesting problem in that the application works fine on my local machine but when I upload it to azure websites I suddenly get a CORS error and I'm unsure of the root cause. Interestingly I can log into the application just fine, get the bearer token, but I am unable to access any controller methods. The code below shows localhost but obviously the service name is replaced when I upload to Azure websites.

The error I get is

"XMLHttpRequest cannot load https://tradesservice.azurewebsites.net/api/OpenPnL. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://perseus1.azurewebsites.net' is therefore not allowed access. The response had HTTP status code 500." 

Perseus1 is of course my angular app and tradesservice is my backend API.

The code that makes the request is as follows:

perseusApp.factory('openpnlData', function ($resource,currentUser) {
return $resource('http://localhost:36080/api/OpenPnL/:id', null,
    {
            'get': {
                headers: { 'Authorization': 'Bearer ' + currentUser.getProfile().token },
                isArray: true
            },

            'save': {
                headers: { 'Authorization': 'Bearer ' + currentUser.getProfile().token }
            },

            'update': {
                method: 'PUT',
                headers: { 'Authorization': 'Bearer ' + currentUser.getProfile().token }
            }
        });

});

basically my controller calls the angular service for the data after the user is authenticated.

the controller code is currently configured to allow requests from anywhere.

namespace TradesService.Controllers
{
[Authorize]
[EnableCors(origins: "*", headers: "*", methods: "*")]
public class OpenPnLController : ApiController
{
    private benderEntities db = new benderEntities();

    // GET: api/OpenPnL
    public IQueryable<OpenPnL> GetOpenPnL()
    {
        return db.OpenPnL;
    }

    // GET: api/OpenPnL/5
    [ResponseType(typeof(OpenPnL))]
    public IHttpActionResult GetOpenPnL(int id)
    {
        OpenPnL openPnL = db.OpenPnL.Find(id);
        if (openPnL == null)
        {
            return NotFound();
        }

        return Ok(openPnL);
    }

and my WebAPIConfig does enable CORS

    public static void Register(HttpConfiguration config)
    {
        // Web API configuration and services
        // Configure Web API to use only bearer token authentication.
        config.EnableCors();
        config.SuppressDefaultHostAuthentication();
        config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));

        // Web API routes
        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }
}

as well as I enable it for the token service as well

    public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
    {
        context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });
        var userManager = context.OwinContext.GetUserManager<ApplicationUserManager>();

        ApplicationUser user = await userManager.FindAsync(context.UserName, context.Password);

        if (user == null)
        {
            context.SetError("invalid_grant", "The user name or password is incorrect.");
            return;
        }

The request looks like this

Accept:application/json, text/plain, */*
Accept-Encoding:gzip, deflate, sdch
Accept-Language:en-US,en;q=0.8
Authorization:Bearer Rlau_KVh9WUjrVw1smLaJjkR3G_nT1mUlliGVFW8YwoGQjL4RUyozVug7bXiFrdQQAKWowDlx2OpTbUYbL3XS_pouVQMT6YYzNDxb67byWg1szpuDTt-f3XAakKf0ilLN-0T1CI8dDO5PWewBzA7B3mbI0XNGvfZpPpZc_f5orVW4RC58OqTm35Brh73_lOPtlLrdG3rQwqUIHTI6Tqi69TXdl8D8I7KjTo5ruboIpGJHvqQOF38Flqvskdh4M6ottajp3znE4SToil78yOrZ9oPmeFemdpVde9UpTJRcDqF2tVf-9eALorym6cYYWBoji11chr594lsTp0IW30_Xa9uyxwDIOSgEGGxWzbFBuE6fKzpTy49dSW-kxD6mii-M7eW1D_aFdXVEp8IsTbLL6Pa5o_i3izsFR2MajfWFu-KwzOcWJ0SL38XAIz12ouq6ifnRZQe4ezOZkc5ckgy1T86xVVa0z4q0_2jsx-TCYw
Cache-Control:no-cache
Connection:keep-alive
Host:tradesservice.azurewebsites.net
Origin:https://perseus1.azurewebsites.net
Pragma:no-cache
Referer:https://perseus1.azurewebsites.net/openpnl
User-Agent:Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36

the response I get is

HTTP/1.1 500 Internal Server Error
Cache-Control: private
Content-Length: 36
Content-Type: application/json; charset=utf-8
Server: Microsoft-IIS/8.0
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Set- Cookie:ARRAffinity=b0cea33dbc4e2efdaae3fe9feccd731de0b41e0e9fe1259e0169810645b448f9;Path=/;Domain=tradesservice.azurewebsites.net
Date: Tue, 06 Oct 2015 23:15:21 GMT

the javascript console in chrome shows the following.

XMLHttpRequest cannot load https://tradesservice.azurewebsites.net/api/OpenPnL. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://perseus1.azurewebsites.net' is therefore not allowed access. The response had HTTP status code 500.

Any thoughts on what i'm doing wrong here?

update

someone mentioned the server config might be an issue. Here are the relevant sections of the web.config for the web api

  <system.web>
    <authentication mode="None" />
    <compilation debug="true" targetFramework="4.5.2" />
    <httpRuntime targetFramework="4.5.2" />

  </system.web>
  <system.webServer>
    <modules>
      <remove name="FormsAuthentication" />
    </modules>
    <handlers>
      <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
      <remove name="OPTIONSVerbHandler" />
      <remove name="TRACEVerbHandler" />
      <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
    </handlers>
  </system.webServer>

and the website hosting the angular code

<configuration>

    <system.web>
      <compilation debug="true" targetFramework="4.5.2" />
      <httpRuntime targetFramework="4.5.2" />
    </system.web>
  <system.webServer>
    <httpProtocol>
      <customHeaders>
        <add name="Access-Control-Allow-Origin" value="*" />
        <add name="Access-Control-Allow-Methods" value="GET,POST,DELETE,HEAD,PUT,OPTIONS" />
        <add name="Access-Control-Allow-Headers" value="Origin, X-Olaround-Debug-Mode, Authorization, Accept" />
        <add name="Access-Control-Expose-Headers" value="X-Olaround-Debug-Mode, X-Olaround-Request-Start-Timestamp, X-Olaround-Request-End-Timestamp, X-Olaround-Request-Time, X-Olaround-Request-Method, X-Olaround-Request-Result, X-Olaround-Request-Endpoint" />
      </customHeaders>
    </httpProtocol>
  </system.webServer>
</configuration>

I modified the web.config to include the body listed above and now the request looks like this

Added the code to my web.config for the website and now the request looks like this..

OPTIONS /api/OpenPnL HTTP/1.1
Host: tradesservice.azurewebsites.net
Connection: keep-alive
Pragma: no-cache
Cache-Control: no-cache
Access-Control-Request-Method: GET
Origin: https://perseus1.azurewebsites.net
User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36
Access-Control-Request-Headers: accept, authorization
Accept: */*

Referer: https://perseus1.azurewebsites.net/openpnl
Accept-Encoding: gzip, deflate, sdch
Accept-Language: en-US,en;q=0.8  

and response

HTTP/1.1 200 OK
Allow: OPTIONS, TRACE, GET, HEAD, POST
Content-Length: 0
Server: Microsoft-IIS/8.0
Public: OPTIONS, TRACE, GET, HEAD, POST
X-Powered-By: ASP.NET
Set-Cookie: ARRAffinity=b0cea33dbc4e2efdaae3fe9feccd731de0b41e0e9fe1259e0169810645b448f9;Path=/;Domain=tradesservice.azurewebsites.net
Date: Tue, 06 Oct 2015 23:59:16 GMT

no more 500 error.

3
  • there's no CORS headers in the response, but it's not (necessarily) a CORS error, there's some sort of Internal Server Error as indicated in the 500 response Oct 6, 2015 at 23:21
  • 2
    make sure it is accepting OPTIONS requests
    – charlietfl
    Oct 6, 2015 at 23:23
  • As stated, take a look at the network tab and check on OPTIONS header
    – user4164128
    Oct 6, 2015 at 23:47

0

Your Answer

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