Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AllowAnyOrigin Cors Not working Axios Vuejs

I have a server that I have set up, running in production, we have tons of applications calling this web server. The code below is to demonstrate that it allows any origin requests.

 public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
        loggerFactory.AddConsole(Configuration.GetSection("Logging"));
        loggerFactory.AddDebug();

        app.UseExceptionHandler("/Home/Error");

        app.UseStaticFiles();

        app.UseCors(builder =>
        {
            builder.AllowAnyOrigin()
                    .AllowAnyMethod()
                    .AllowAnyHeader();
        });

This works for all servers currently set up. It's on our internal network, and other servers internally will use this service.

I am creating a proof of concept to try and modernize our Applications slowly by using Vue. Except this axios request is getting an error. The other servers that call this method are using .net as well, but it should build the same request.

Here is the error.

Failed to load https://{server}/api/application/36626: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access.

This is obviously crazy talk by axios. I allow for any origin. I can't imagine we only want to use 'simple-requests' so the w3 standard for simple requests might not work. I thought maybe this could be an incorrect error considering this is an octet-stream returned from the server. The code is below.

<script>
import axios from 'axios'

export default {
  name: 'AppList',
  data () {
    return {
      applist: [],
      errors: []
    }
  },
  created: function() {
    axios.get('https://{server}/api/application/36626')
      .then(r => { console.log(response); })
      .catch(ex => {
        this.errors.push(ex);
      })
  }
}
</script>

EDIT I have full rights to this machine, I have confirmed I can use a Postman GET request from my local machine with no problem.

Edit 2 Working curl command curl -X GET --header 'Accept: application/octet-stream' 'https://{server}/api/Application/36626'

like image 475
christopher clark Avatar asked Mar 07 '23 14:03

christopher clark


2 Answers

It turns out the .Net Core Server was not set up right, it wasn't until I was trying to use the browser on my local machine did the CORS problem crop up.

I'm not sure if the CORS implementation changed and I was not aware, or if I just wasn't doing it right from the start, but I was sure I followed guides.

The first thing I changed was ensuring that the Cors Policy was added before configuring the app to use MVC.

The second thing I did, and I suspect this is optional, but best practice, I also moved the policy logic to the ConfigureServices method.

My final code looked below. I'm keeping as much in tact to preserve the order.

 public void ConfigureServices(IServiceCollection services)
        {
            // Add framework services.
            services.AddCors(options =>
            {
                options.AddPolicy("CorsPolicy",
                    builder => builder.AllowAnyOrigin()
                    .AllowAnyMethod()
                    .AllowAnyHeader()
                    .AllowCredentials());
            });
            services.AddOptions();
            services.AddSwaggerGen();
            ///Authentication configuration went here.
            services.AddSingleton<IConfiguration>(Configuration);
            services.AddMvc();

        }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        loggerFactory.AddConsole(Configuration.GetSection("Logging"));
        loggerFactory.AddDebug();

        app.UseExceptionHandler("/Home/Error");
        app.UseStaticFiles();
        app.UseCors("CorsPolicy");

        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
        });

        app.UseSwagger((httpRequest, swaggerDoc) =>
        {
            swaggerDoc.Host = httpRequest.Host.Value;

        });
        app.UseSwaggerUi(swaggerUrl: "/{appname}/swagger/v1/swagger.json");
like image 155
christopher clark Avatar answered Mar 15 '23 21:03

christopher clark


Activating the cors didn't work for me for the PUT and DELETE methods, what I did was add some configuration lines in the web.config file to remove the WebDav module.

I used this inside the existing tag system.webServer tag in the web.config file

<modules runAllManagedModulesForAllRequests="false">
    <remove name="WebDAVModule" />
</modules>

I found the lines in this site:

Modify the web.config https://hovercraft.ie/asp-net-core-web-api-put-delete-methods-not-allowed-405-error/

Hope this helps.

like image 43
Luis Avatar answered Mar 15 '23 21:03

Luis