PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0
Showing posts with label cors. Show all posts
Showing posts with label cors. Show all posts

Thursday, October 13, 2022

[FIXED] Why the same GET request gets blocked by CORS when called within javascript but allowed from HTML src?

 October 13, 2022     axios, cors, fetch, javascript, react-query     No comments   

Issue

I was embedding some large images with react query to provide a loading effect on slow connections when I encountered this CORS issue I did not understand.

I'm not getting why it's no problem for the browser to import resources from external servers when the request is performed in the HTML.
For example, this is a valid image fetch:
<img src={"https://stackoverflow.design/assets/img/logos/so/logo-stackoverflow.svg"}/>
it gets rendered with no problem.

When performing the same fetch from javascript, you get CORS to block your response.
For example:
fetch("https://stackoverflow.design/assets/img/logos/so/logo-stackoverflow.svg");
will be blocked.

They are both GET requests, and inspecting the response headers on the network tab they look the exact same.

Is it a desired browser behavior? If so, how is it a safety feature?
If not, how to get around this, in order to fetch simple requests?


Solution

Is it a desired browser behavior? If so, how is it a safety feature?

Keep in mind that the image might not be generally available. It could be password protected, or on a company intranet. Consider a hypothetical popular Intranet application that has a common URL that displays internal company financial data on a graph.

When you use fetch the image data is made available to JavaScript. The JavaScript can then do whatever it likes with the image, including sending it to the person who wrote the JavaScript. That hypothetical financial data would be leaked.

When you use an <img> element, the image is just displayed in the page and the user can see it. The security problems are low and JavaScript can't access the data in the image.

Adding a crossorigin attribute to the <img> would let JavaScript access the data in it … and would also require permission from CORS before the image could be displayed.

If not, how to get around this, in order to fetch simple requests?

Grant permission with CORS or fetch the image with code that isn't running client-side in a browser.



Answered By - Quentin
Answer Checked By - Cary Denson (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Thursday, September 8, 2022

[FIXED] How to enable CORS in Rails 4 App

 September 08, 2022     ajax, cors, ruby, ruby-on-rails, ruby-on-rails-4     No comments   

Issue

I'm just about to pull my hair out... I've been trying to enable CORS in this Rails app since the morning and it just doesn't work. I've tried this, using Rack Cors Gem, this answer and this post all without success.

Can someone point me in the right direction?

Here's my js:

      var req = new XMLHttpRequest();

      if ('withCredentials' in req) {
            // req.open('GET', "https://api.github.com/users/mralexgray/repos", true);
            req.open('GET', "http://www.postcoder.lc/postcodes/" + value, true);
            // Just like regular ol' XHR
            req.onreadystatechange = function() {
                if (req.readyState === 4) {
                    if (req.status >= 200 && req.status < 400) {
                        // JSON.parse(req.responseText) etc.
                        console.log(req.responseText);
                    } else {
                        // Handle error case
                    }
                }
            };
            req.send();
        }

When I try this url (from an external client): https://api.github.com/users/mralexgray/repos that works ok, I'm assuming the problem is with my Rails API. Am I wrong?

EDIT: Currently I have this in my controller:

skip_before_filter :verify_authenticity_token
before_filter :cors_preflight_check
after_filter :cors_set_access_control_headers

# For all responses in this controller, return the CORS access control headers.
def cors_set_access_control_headers
  headers['Access-Control-Allow-Origin'] = '*'
  headers['Access-Control-Allow-Methods'] = 'POST, GET, OPTIONS'
  headers['Access-Control-Max-Age'] = "1728000"
end

# If this is a preflight OPTIONS request, then short-circuit the
# request, return only the necessary headers and return an empty
# text/plain.

def cors_preflight_check
  headers['Access-Control-Allow-Origin'] = '*'
  headers['Access-Control-Allow-Methods'] = 'POST, GET, OPTIONS'
  headers['Access-Control-Allow-Headers'] = 'X-Requested-With, X-Prototype-Version'
  headers['Access-Control-Max-Age'] = '1728000'
end

Solution

You should use rack cors

It provides a nice DSL, to use in your config/application.rb, instead of the messy header work and before filters.

A very permissive would be as follows, but of course, you'll have to tailor it a bit.

use Rack::Cors do
  allow do
    origins '*'
    resource '*', headers: :any, methods: :any
  end  
end


Answered By - apneadiving
Answer Checked By - Terry (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Thursday, September 1, 2022

[FIXED] Why CORS error come out when I call an API?

 September 01, 2022     cors, javascript, nginx, nginx-reverse-proxy     No comments   

Issue

I deployed a project which has two APIs, login and loadMenu respectively, to a server. When I call the login API, everything is fine and I get the result.

But when I try to call the loadMenu API, a CORS problem comes out.

and here is my nginx configuration file:

server {
  listen 80;
  # set proper server name after domain set
  server_name xxxxxx;

  # Add Headers for odoo proxy mode
  proxy_set_header X-Forwarded-Host $host;
  proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
  proxy_set_header X-Forwarded-Proto $scheme;
  proxy_set_header X-Real-IP $remote_addr;
  add_header X-Frame-Options "SAMEORIGIN";
  add_header X-XSS-Protection "1; mode=block";
  proxy_set_header X-Client-IP $remote_addr;
  proxy_set_header HTTP_X_FORWARDED_HOST $remote_addr;

  #   odoo    log files
  access_log  /var/log/nginx/odoo15-access.log;
  error_log       /var/log/nginx/odoo15-error.log;

  #   increase    proxy   buffer  size
  proxy_buffers   16  64k;
  proxy_buffer_size   128k;

  proxy_read_timeout 900s;
  proxy_connect_timeout 900s;
  proxy_send_timeout 900s;

  #   force   timeouts    if  the backend dies
  proxy_next_upstream error   timeout invalid_header  http_500    http_502
  http_503;

  types {
    text/less less;
    text/scss scss;
  }

  #   enable  data    compression
  gzip    on;
  gzip_min_length 1100;
  gzip_buffers    4   32k;
  gzip_types  text/css text/less text/plain text/xml application/xml application/json 
  application/javascript application/pdf image/jpeg image/png;
  gzip_vary   on;
  client_header_buffer_size 4k;
  large_client_header_buffers 4 64k;
  client_max_body_size 0;

    add_header 'Access-Control-Allow-Origin' "$http_origin" always;
    add_header 'Access-Control-Allow-Credentials' 'true' always;
  location / {
    #add_header 'Access-Control-Allow-Origin' "$http_origin" always;
    #add_header 'Access-Control-Allow-Credentials' 'true' always;
    if ($request_method = OPTIONS) {
        add_header 'Access-Control-Allow-Origin' "$http_origin"; # DO NOT remove THIS LINES (doubled with outside 'if' above)
        add_header 'Access-Control-Allow-Credentials' 'true';
        add_header 'Access-Control-Max-Age' 1728000; # cache preflight value for 20 days
        add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
        add_header 'Access-Control-Allow-Headers' 'My-First-Header,My-Second-Header,Authorization,Content-Type,Accept,Origin';
        add_header 'Content-Length' 0;
        add_header 'Content-Type' 'text/plain charset=UTF-8';
       return 204;
    }
    if ($request_method = POST) {
        add_header 'Access-Control-Allow-Origin' "$http_origin";
        add_header 'Access-Control-Allow-Credentials' 'true';
        add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
        add_header 'Access-Control-Allow-Headers' *;
    }
    #proxy_set_header host $http_host;    
    proxy_pass    http://127.0.0.1:8069;
    # by default, do not forward anything
    proxy_redirect off;
    proxy_cookie_path / "/; secure; HttpOnly;SameSite=None";
  }


  location /longpolling {
  proxy_pass http://127.0.0.1:8072;
  }
  location ~* .(js|css|png|jpg|jpeg|gif|ico)$ {
  expires 2d;
  proxy_pass http://127.0.0.1:8069;
  add_header Cache-Control "public, no-transform";
  }
  # cache some static data in memory for 60mins.
  location ~ /[a-zA-Z0-9_-]*/static/ {
  proxy_cache_valid 200 302 60m;
  proxy_cache_valid 404      1m;
  proxy_buffering    on;
  expires 864000;
  proxy_pass    http://127.0.0.1:8069;
  }
}

and here is the error message

Access to fetch at 'http://127.0.0.1:8069/web/login?redirect=http%3A%2F%2F127.0.0.1%3A8069%2Fweb%2Fwebclient%2Fload_menus%2F1652856182783' (redirected from 'http://IP/web/webclient/load_menus/1652856182783') from origin 'http://localhost:8069' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.


Solution

Taking a stab-in-the-dark here but I'm guessing your API at 127.0.0.1:8069 (on the server) is responding with a fully-qualified redirect URL, eg

< HTTP/1.1 302 Found
< Location: http://127.0.0.1:8069/web/login?...

This obviously isn't a URL accessible to anything outside the server's internal network.

What you're missing is a proxy_redirect configuration to rewrite the Location response headers to use the external address...

proxy_redirect default;

# or the more verbose equivalent
# proxy_redirect http://127.0.0.1:8069 /;

As mentioned on your last attempt at this question, it's usually a sign of something wrong with your API design if it responds with 301 / 302 redirect.



Answered By - Phil
Answer Checked By - David Marino (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Friday, August 5, 2022

[FIXED] How can I allow multiple domains in a .Net Web API with OAuth token authentication using CORS?

 August 05, 2022     asp.net-web-api2, cors, oauth, webapi     No comments   

Issue

We have a .Net Framework Web API, with Token based OAuth authentication, and are trying to make a call to it via an Exchange HTML Add-In. I wish to allow access to several domains, as we may be using several different apps to access it, but we do not wish to allow general (*) access, as it is a proprietary web API, so there is no need for it to be accessed beyond known domains.

I have tried the following in order to satisfy the pre-flight:

  • Add the Access-Control-Allow-Origin headers with multiple domains via <system.webServer> - this returns a "header contains multiple values" CORS error when including multiple domains
  • Adding the Access-Control-Allow-Origin headers with multiple domains via a PreflightRequestsHandler : Delegating Handler - same result

If I set these up with one domain, and used the config.EnableCors with an EnableCorsAttribute with the domains, it would add those on to the headers and give an error with redundant domains.

How can I set up my Web API with OAuth and CORS settings for multiple domains?


Solution

You can add the header "Access-Control-Allow-Origin" in the response of authorized sites in Global.asax file

using System.Linq;
        
private readonly string[] authorizedSites = new string[]
{
  "https://site1.com",
  "https://site2.com"
};

private void SetAccessControlAllowOrigin() 
{
  string origin = HttpContext.Current.Request.Headers.Get("Origin");

  if (authorizedSites.Contains(origin)) 
      HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", origin);
}

protected void Application_BeginRequest() 
{
  SetAccessControlAllowOrigin();
}


Answered By - boubkhaled
Answer Checked By - Pedro (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] why do i get a this cors error from using socket.io

 August 05, 2022     cors, node.js, socket.io     No comments   

Issue

I am using react and express js but when trying to get the socket io to connect to the client from the server I get a cors error:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:8080/socket.io/?EIO=4&transport=polling&t=O6YJzcv. (Reason: CORS header ‘Access-Control-Allow-Origin’ does not match ‘http://localhost:3000/’)

The code from the backend looks like this:

const express = require('express');
const { createServer } = require('http');
const { Server } = require('socket.io');
const cors = require('cors')
 
const app = express();
const httpServer = createServer(app);
const io = new Server(httpServer, {
    cors: {
        origin: 'http://localhost:3000/',
        methods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE'],
        allowedHeaders: ['Content-Type', 'Authorization'],
        credentials: true
    }
});

app.use(cors())

io.on('connection', socket => {
  console.log('connection to derver')
})

httpServer.listen(8080)

And the code from the client like this:

import { useState, useEffect } from 'react';
import axios from 'axios';

import { io } from "socket.io-client";
const socket = io("http://localhost:8080", {
  withCredentials: true,
  extraHeaders: {
    "my-custom-header": "abcd"
  }
});

function App() {

  return (
    <div className="App">
      <form >
        <label>dummy text</label>
      </form>
    </div>
  );
}

export default App;

I dont know what is causing the error and I have been trying to debug it but only got so far. Tried finding other peoples code seing if that would work but copying havent solved it. I would preciate all the help i could get.


Solution

If you change the client socket.io initialization to only use a webSocket, then you won't have CORs issues because webSocket connections are not subject to CORs. But, by default, socket.io starts a connection with several regular http requests which are subject to CORs. So, you can tell socket.io to just start immediately with a webSocket connection by adding the transports option like this:

const socket = io("http://localhost:8080", {
  withCredentials: true,
  extraHeaders: {
    "my-custom-header": "abcd"
  },
  transports: ["websocket"]
});

P.S. One cause of CORs issues in your code is your use of a custom header which is not explicitly enabled for CORs access and triggers CORs pre-flight authorization. But, if you configure it to just use the webSocket transport from the beginning, then you don't have to worry about any of that CORs stuff.



Answered By - jfriend00
Answer Checked By - Marilyn (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Sunday, July 3, 2022

[FIXED] How to enable 'Access-Control-Allow-Origin' header for all files in a directory of XAMPP?

 July 03, 2022     apache, construct-2, cors, cross-domain, xampp     No comments   

Issue

I am developing a HTML5 Javascript app to get an image from my local server which runs on the same machine as the app. When I run the app on my Chrome, I got:

Access to Image at 'http://localhost/someDIrectory/1.jpg' from origin 'http://localhost:50000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:50000' is therefore not allowed access.

From many questions here, the answers point out that I need to set

header("Access-Control-Allow-Origin: *");

in php file and it should work, but that is for php files... What about an image or a directory with images?

I have also came across How do I enable cross-origin resource sharing on XAMPP? and tried to add

<IfModule C:\xampp\htdocs\someDIrectory\1.jpg>
    Header set Access-Control-Allow-Origin: *
</IfModule>

into httpd.conf. I tried restart XAMPP and retried the above. But the result I got is still the same.

How to correctly set up such setting for XAMPP?

Note: I am using Construct 2 which is basically exported out as an HTML5/Javascript. I am simply using Sprite Load From URL action.


Solution

Create a file called ".htaccess" in the directory of your files and add the following to the file.

Header set Access-Control-Allow-Origin "http://localhost:50000/"


Answered By - neville
Answer Checked By - Clifford M. (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Friday, June 24, 2022

[FIXED] How to enable CORS in Nginx proxy server?

 June 24, 2022     cors, nginx, node.js, reverse-proxy     No comments   

Issue

As my title, here is the config file located in conf.d/api-server.conf

server {
  listen 80;
  server_name api.localhost;

  location / {
    add_header 'Access-Control-Allow-Origin' 'http://api.localhost';
    add_header 'Access-Control-Allow_Credentials' 'true';
    add_header 'Access-Control-Allow-Headers' 'Authorization,Accept,Origin,DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range';
    add_header 'Access-Control-Allow-Methods' 'GET,POST,OPTIONS,PUT,DELETE,PATCH';

    if ($request_method = 'OPTIONS') {
      add_header 'Access-Control-Max-Age' 1728000;
      add_header 'Content-Type' 'text/plain charset=UTF-8';
      add_header 'Content-Length' 0;
      return 204;
    }

    proxy_redirect off;
    proxy_set_header host $host;
    proxy_set_header X-real-ip $remote_addr;
    proxy_set_header X-forward-for $proxy_add_x_forwarded_for;
    proxy_pass http://127.0.0.1:3000;
  }
}

The nginx.conf file stay the same as default.

After I send request to api.localhost (api.localhost/admin/login), I still receive 405 error:

XMLHttpRequest cannot load http://api.localhost/admin/login. Response 
to preflight request doesn't pass access control check: No 'Access-
Control-Allow-Origin' header is present on the requested resource. 
Origin 'http://admin.localhost:3000' is therefore not allowed access. 
The response had HTTP status code 405.

That is the response from server That's the request looks like


Solution

The issue is that your if condition is not going to send the headers in the parent in /. If you check the preflight response headers it would be

HTTP/1.1 204 No Content
Server: nginx/1.13.3
Date: Fri, 01 Sep 2017 05:24:04 GMT
Connection: keep-alive
Access-Control-Max-Age: 1728000
Content-Type: text/plain charset=UTF-8
Content-Length: 0

And that doesn't give anything. So two possible fixes for you. Copy the add_header inside if block also

server {
  listen 80;
  server_name api.localhost;

  location / {
    add_header 'Access-Control-Allow-Origin' 'http://api.localhost';
    add_header 'Access-Control-Allow-Credentials' 'true';
    add_header 'Access-Control-Allow-Headers' 'Authorization,Accept,Origin,DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range';
    add_header 'Access-Control-Allow-Methods' 'GET,POST,OPTIONS,PUT,DELETE,PATCH';

    if ($request_method = 'OPTIONS') {
      add_header 'Access-Control-Allow-Origin' 'http://api.localhost';
      add_header 'Access-Control-Allow-Credentials' 'true';
      add_header 'Access-Control-Allow-Headers' 'Authorization,Accept,Origin,DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range';
      add_header 'Access-Control-Allow-Methods' 'GET,POST,OPTIONS,PUT,DELETE,PATCH';
      add_header 'Access-Control-Max-Age' 1728000;
      add_header 'Content-Type' 'text/plain charset=UTF-8';
      add_header 'Content-Length' 0;
      return 204;
    }

    proxy_redirect off;
    proxy_set_header host $host;
    proxy_set_header X-real-ip $remote_addr;
    proxy_set_header X-forward-for $proxy_add_x_forwarded_for;
    proxy_pass http://127.0.0.1:3000;
  }
}

Or you can move it outside the location block, so every request has the response

server {
   listen 80;
   server_name api.localhost;

   add_header 'Access-Control-Allow-Origin' 'http://api.localhost';
   add_header 'Access-Control-Allow-Credentials' 'true';
   add_header 'Access-Control-Allow-Headers' 'Authorization,Accept,Origin,DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range';
   add_header 'Access-Control-Allow-Methods' 'GET,POST,OPTIONS,PUT,DELETE,PATCH';

  location / {

    if ($request_method = 'OPTIONS') {
      add_header 'Access-Control-Max-Age' 1728000;
      add_header 'Content-Type' 'text/plain charset=UTF-8';
      add_header 'Content-Length' 0;
      return 204;
    }

    proxy_redirect off;
    proxy_set_header host $host;
    proxy_set_header X-real-ip $remote_addr;
    proxy_set_header X-forward-for $proxy_add_x_forwarded_for;
    proxy_pass http://127.0.0.1:3000;
  }
}

If you only want to allow certain locations in your config for CORS. like /api then you should create a template conf with your headers

 add_header 'Access-Control-Allow-Origin' 'http://api.localhost';
 add_header 'Access-Control-Allow-Credentials' 'true';
 add_header 'Access-Control-Allow-Headers' 'Authorization,Accept,Origin,DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range';
 add_header 'Access-Control-Allow-Methods' 'GET,POST,OPTIONS,PUT,DELETE,PATCH';

and then use

include conf.d/corsheaders.conf;

in your OPTIONS block and /api block. So CORS are only allowed for the /api. If you don't care which location for CORS then you can use the second approach of moving core headers to server block



Answered By - Tarun Lalwani
Answer Checked By - Clifford M. (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Thursday, May 19, 2022

[FIXED] How do API work with CORS policies to serve multiple apps

 May 19, 2022     ajax, cors, web-services     No comments   

Issue

I am creating an API that would serve data to my frontend app. The API is on api.myapp.com and the app on www.myapp.com (same domain, just another subdomain). They communicate with AJAX requests and CORS is all set up, working fine.

But I have another app on another domain (www.myotherapp.com) which partialy uses the same data as myapp, so I was thinking of reusing the API so myotherapp could requests data from it too.

I think it is one use case of API, to be reusable, right?

But then, there is something that I may have missed, because as my API has CORS enabled with "Access-Control-Allow-Origin: www.myapp.com", it won't allow other apps to use its endpoints, right? Their AJAX requests would fail with CORS policies.

So how are public API built and configured? How should I set my API so it can serve several apps (ideally, only the ones I allow)?

Thanks for the explanations :)


Solution

There is an Origin header in the request and your API should check if this header is one of the allowed. If it is, then return it as an Access-Control-Allow-Origin header.

If the API is public, it can returns * as Access-Control-Allow-Origin header.



Answered By - justMatys
Answer Checked By - Senaida (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Tuesday, March 15, 2022

[FIXED] Http calls are immediately cancelled

 March 15, 2022     angular, cakephp-3.0, cors     No comments   

Issue

I have an angular 4 front end with a CakePHP 3 backend. When I make a request to an API end point using my browser or Rest Client I receive a response. But when I send the response from the angular service it immediately shows cancelled in the network.

At first I assumed it was a CORS issue. I have tried both with and without CORS enabled. I also added $this->Security->csrfCheck = false; to my AppController.php which led me to believe that the local server is never hit (no breakpoints were firing).

So instead I am looking at Angular side of the equation. I have attempted to set my headers but that also does not work.

import { Headers, Http, Response, RequestOptions } from '@angular/http';

login(loginData) {
    const headers = new Headers({'Content-Type': 'application/json'});

    const url:string = this.backendUrl + '/auth/login/?';

    return this.Http.post(
        url,
        JSON.stringify(loginData),
        { headers: headers }
    ).map(
        res => res.json
    ).map(
        response => function(response) {
            ...
        },
        error => function(error) {
            ...
        }
    );
}

I am in the process of migrating from 1 to 4. So I know that it worked in Angular 1 using $http requests.

function login(loginData) {
   var = this.backendUrl + '/auth/login/?';

   $http.post(url, loginData).then( ... );
}

Here is my component which uses the subscription:

login = function(activeUser):ActiveUser|boolean {
    this.isLoggingIn = true;

    return this.LoginService.login(activeUser).subscribe(
        activeUser => function(activeUser) {
            if (activeUser) {
                this.activeUser = activeUser;
            } else {
                this.reset();
            }

            return activeUser;
        }.bind(this)
    ).complete(
        function() {
            this.isLoggingIn = false;
        }.bind(this)
    );
};

Solution

The problem had to do with how Angular $http now handles CORS requests. In the updated version there are two requests sent, an OPTIONS request and then the actual GET/POST request. So I had to change my backend to return a 200 on the OPTIONS without executing the command and instead execute on the second request.



Answered By - Jeremy
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Tuesday, March 1, 2022

[FIXED] Response to preflight request doesn't pass access control check Laravel and Ajax call

 March 01, 2022     cors, cross-domain, javascript, jquery, laravel-5.1     No comments   

Issue

I have a REST api made in Laravel 5.1 hosted in a remote server. Now, I', trying to consume that API from another website (that I have in local).

In Laravel I set the required lines to send the CORS headers. I also tested the API using Postman and everything seems to be ok!

In the Frontend

Then, in the website I sent the POST request using ajax, with this code:

var url="http://xxx.xxx.xxx.xxx/apiLocation";
var data=$("#my-form").serialize();
    $.ajax({
                    type: "POST",
                    url: url,
                    data: data,
                    headers: { 'token': 'someAPItoken that I need to send'},
                    success: function(data) {
                        console.log(data);
                    },
                    dataType: "json",
                }); 

Buy then I get this error in the console:

XMLHttpRequest cannot load http://xxx.xxx.xxx.xxx/apiLocation. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is therefore not allowed access.

In the Backend

In the API I set this (using a Laravel Middleware to set the headers):

return $next($request)
            ->header('Access-Control-Allow-Origin', '*')
            ->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');

So, I'm confused about where is exactly the problem.

  1. In the server? but then why with Postman work fine?
  2. Is in the Ajax call? so, then what should I add?

Solution

Your backend code must include some explicit handling for OPTIONS requests that sends a 200 response with just the configured headers; for example:

if ($request->getMethod() == "OPTIONS") {
    return Response::make('OK', 200, $headers);
}

The server-side code also must send an Access-Control-Allow-Headers response header that includes the name of the token request header your frontend code is sending:

-> header('Access-Control-Allow-Headers', 'token')

but then why with Postman work fine?

Postman isn’t a web app and isn’t bound by same-origin restrictions placed on web apps by browsers to block them from making cross-origin requests. Postman is a browser bolt-on for convenience of testing requests in the same way they could be made outside the browser using curl or whatever from the command line. Postman can freely make cross-origin requests.

https://developer.mozilla.org/docs/Web/HTTP/Access_control_CORS in contrast explains how browsers block web apps from making cross-origin requests but also how you can un-block browsers from doing that by configuring your backend to send the right CORS headers.

https://developer.mozilla.org/docs/Web/HTTP/Access_control_CORS#Preflighted_requests explains why the browser is sending that OPTIONS request your backend needs to handle.



Answered By - sideshowbarker
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Monday, February 21, 2022

[FIXED] Receiving CORS policy error on every API request nuxtJS

 February 21, 2022     cors, laravel, laravel-8, nuxtjs2     No comments   

Issue

Im trying to run a Laravel V8.14(Backend) and nuxtJS 2.15(Frontend) app but unfortunately every API request (including SSR ones) are getting CORS policy error on my LOCAL computer using WAMP

Running npm run dev everything gets compiled and it starts listening on http://localhost:3000/ . No Errors on the console or command prompt when Im trying to access my homepage.but the api requests getting CORS policy error. I have tried baseURL and proxy with nuxtJS but the error stay the same all the time.I am aware you cannot have these two at the same time

Laravel cors.php config file

<?php

return [

    /*
    |--------------------------------------------------------------------------
    | Laravel CORS Options
    |--------------------------------------------------------------------------
    |
    | The allowed_methods and allowed_headers options are case-insensitive.
    |
    | You don't need to provide both allowed_origins and allowed_origins_patterns.
    | If one of the strings passed matches, it is considered a valid origin.
    |
    | If array('*') is provided to allowed_methods, allowed_origins or allowed_headers
    | all methods / origins / headers are allowed.
    |
    */

    /*
     * You can enable CORS for 1 or multiple paths.
     * Example: ['api/*']
     */
   'paths' => ['api/*'],

    /*
    * Matches the request method. `[*]` allows all methods.
    */
    'allowed_methods' => ['*'],

    /*
     * Matches the request origin. `[*]` allows all origins. Wildcards can be used, eg `*.mydomain.com`
     */
    'allowed_origins' => ['*'],

    /*
     * Patterns that can be used with `preg_match` to match the origin.
     */
    'allowed_origins_patterns' => [],

    /*
     * Sets the Access-Control-Allow-Headers response header. `[*]` allows all headers.
     */
    'allowed_headers' => ['*'],

    /*
     * Sets the Access-Control-Expose-Headers response header with these headers.
     */
    'exposed_headers' => [],

    /*
     * Sets the Access-Control-Max-Age response header when > 0.
     */
    'max_age' => 0,

    /*
     * Sets the Access-Control-Allow-Credentials header.
     */
    'supports_credentials' => false,
];

nuxt.config.js file

     axios:{
     //baseURL : process.env.CLIENT_URL, //Cant be used with proxy
     proxy:true,
        browserBaseURL: process.env.CLIENT_URL + '/api', // client url
      prefix: '/api/',
            common: {
                'Content-Type': 'application/x-www-form-urlencoded',
                'Accept': 'application/json, text/plain, */*',
            }
            },
            proxy: {
              '/api/': { target: 'http://api.localhost/', pathRewrite: {'^/api/': ''}, changeOrigin: true }
            },

Laravel Kernel.php

<?php

namespace App\Http;

use Illuminate\Foundation\Http\Kernel as HttpKernel;

class Kernel extends HttpKernel
{
    /**
     * The application's global HTTP middleware stack.
     *
     * These middleware are run during every request to your application.
     *
     * @var array
     */
    protected $middleware = [
     \Fruitcake\Cors\HandleCors::class,
        \App\Http\Middleware\TrustProxies::class,
        \App\Http\Middleware\CheckForMaintenanceMode::class,
        \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
        \App\Http\Middleware\TrimStrings::class,
        \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
        \App\Http\Middleware\SetLocale::class,
       ];

    /**
     * The application's route middleware groups.
     *
     * @var array
     */
    protected $middlewareGroups = [
        'web' => [
            // \App\Http\Middleware\EncryptCookies::class,
            \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
            // \Illuminate\Session\Middleware\StartSession::class,
            \Illuminate\Session\Middleware\AuthenticateSession::class,
            // \Illuminate\View\Middleware\ShareErrorsFromSession::class,
            // \App\Http\Middleware\VerifyCsrfToken::class,
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
        ],
'minify' =>[
     \RenatoMarinho\LaravelPageSpeed\Middleware\InlineCss::class,
    \RenatoMarinho\LaravelPageSpeed\Middleware\ElideAttributes::class,
    \RenatoMarinho\LaravelPageSpeed\Middleware\InsertDNSPrefetch::class,
    \RenatoMarinho\LaravelPageSpeed\Middleware\RemoveComments::class,
    \RenatoMarinho\LaravelPageSpeed\Middleware\TrimUrls::class,
    \RenatoMarinho\LaravelPageSpeed\Middleware\RemoveQuotes::class,
    \RenatoMarinho\LaravelPageSpeed\Middleware\CollapseWhitespace::class,
        ],
        'api' => [
            //'throttle:60,1',
            'bindings',
            
        ],
    ];

    /**
     * The application's route middleware.
     *
     * These middleware may be assigned to groups or used individually.
     *
     * @var array
     */
    protected $routeMiddleware = [
          'admin' => \App\Http\Middleware\Adminmiddleware::class,
        'auth' => \App\Http\Middleware\Authenticate::class,
        'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
        'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
        'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
        'can' => \Illuminate\Auth\Middleware\Authorize::class,
        'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
        'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
        'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
        'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
    ];

    /**
     * The priority-sorted list of middleware.
     *
     * This forces non-global middleware to always be in the given order.
     *
     * @var array
     */
    protected $middlewarePriority = [
        \Illuminate\Session\Middleware\StartSession::class,
        \Illuminate\View\Middleware\ShareErrorsFromSession::class,
        \App\Http\Middleware\Authenticate::class,
        \Illuminate\Session\Middleware\AuthenticateSession::class,
        \Illuminate\Routing\Middleware\SubstituteBindings::class,
        \Illuminate\Auth\Middleware\Authorize::class,
    ];
}

The Exact Error

Access to XMLHttpRequest at 'http://localhost/api/dashboard/getusercompanyfresh'
 from origin 'http://localhost:3000' has been blocked by CORS policy: 
Response to preflight request doesn't pass access control check:
 No 'Access-Control-Allow-Origin' header is present on the requested resource.

All the API requests are in laravel api.php in routes folder

Its been 5 days Im stuck in this and mostly Im changing stuff with proxy hoping it works next time.even did a fully fresh installation of nuxtJS(removing node_modules and package.json.lock) but no luck.

Any help would be greatly appreciated.


Solution

The problem was my wamp apache configuration, I'll be explaning the steps I took in order to find what was causing CORS error and how I fixed it.

After installing everything on a fresh windows I was still facing the issue but NOT on a live server so I've figured it must be the web server I'm running and that was the issue.The wrong part of my apache configuration on WAMP was :

  DocumentRoot "${INSTALL_DIR}/www/laravel/"
  <Directory "${INSTALL_DIR}/www/laravel/">

which I had in both httpd.conf and httpd-vhosts.conf.After changing the above to (adding the public folder of laravel) :

  DocumentRoot "${INSTALL_DIR}/www/laravel/public"
  <Directory "${INSTALL_DIR}/www/laravel/public">

Everything started working with the SAME configuration in the question that I posted and CORS policy error was gone.

I have also tested another method which you can remove the proxy and the axios setting in the nuxt.config.js file will be the following :

  axios:{
    baseURL : process.env.CLIENT_URL, //Cant be used with proxy
      browserBaseURL: process.env.CLIENT_URL + '/api', // client url
            common: {
                'Content-Type': 'application/x-www-form-urlencoded',
                'Accept': 'application/json, text/plain, */*',
            }
            },

where CLIENT_URL is a .env laravel file variable and its value is http://localhost in my case and anything proxy related should be commented because you cannot use proxy and baseURL at the same time.

Read More about nuxt axios module here

Keep in mind that you have to have LoadModule headers_module modules/mod_headers.so known as headers_module uncommented in your httpd.conf too

Thanks for all the help along the way



Answered By - Pc Monk
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Friday, February 4, 2022

[FIXED] Access-Control-Allow-Origin (Laravel & Vue) CORS CORB error on localhost

 February 04, 2022     api, cors, laravel, vue.js     No comments   

Issue

I use this package and it didn't work (https://github.com/barryvdh/laravel-cors)

enter image description here

addSMS() {
    axios.post('https://smsmisr.com/api/webapi', {
                headers: {
                        'Access-Control-Allow-Origin': '*',
                        'Access-Control-Allow-Methods': 'POST, GET, PUT, OPTIONS, DELETE',
                        'Access-Control-Allow-Headers': 'Access-Control-Allow-Methods, Access-Control-Allow-Origin, Origin, Accept, Content-Type',
                        'Content-Type': 'application/json',
                        'Accept': 'application/json'
                    },
                username: '*****',
                passowrd: '****',
                etc: '',
            })
            .then(function (response) {
                console.log(response);
            })
            .catch(function (error) {
                console.log(error);
            });
        }

please tell me how to fix it it's cors not working for me.


Solution

As you have no access in API's source code so there is nothing to do with .htaccess or adding 'Access-Control-Allow-Origin': '*', in script. But still you can eradicate this error by opening chrome browser with disabled security mode

In windows run CMD (press together windows button and R key from keyboard. Then type cmd in box and enter).

Secondly go to C drive (in CLI) or where your chrome installed (using cd command) then run following command

“Program Files (x86)\Google\Chrome\Application\chrome.exe” –-allow-file-access-from-files --disable-web-security --user-data-dir --disable-features=CrossSiteDocumentBlockingIfIsolating

It will open your browser in disabled web security mode. Once you done it you can test now with this kind of CORS or CORB error.

note: before running this command make sure there are no chrome are opened already.

Program Files (x86)\Google\Chrome\Application\chrome.exe this should be your chrome installed path

However after opening browser it will show as below, dont panic & dont close this message. if you close this message it will again through this CORS or CORB error enter image description here



Answered By - Rejoanul Alam
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Tuesday, February 1, 2022

[FIXED] Laravel + Vue.js - CORS issue with specific address?

 February 01, 2022     cors, laravel-5, vuejs2     No comments   

Issue

  • Laravel 5.6
  • Vue 2.5.7
  • Google Chrome

Hi, I am trying to understand this CORS issue, i'm still trying to find a way to consume this list: https://api.coinmarketcap.com/v2/listings/, and I receive the following error:

(index):1 Failed to load https://api.coinmarketcap.com/v2/listings/: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://tours.mine' is therefore not allowed access.

yet if I goto this address: https://jsonplaceholder.typicode.com/posts/ everything works fine.

  • After using this Moesif Chrome CORS extension, and thus disabling CORS for chrome, I received a new error: Request header field X-CSRF-TOKEN is not allowed by Access-Control-Allow-Headers in preflight response. received only on this address: https://api.coinmarketcap.com/v2/listings/

  • http://tours.mine - is a local name I set in httpd/vhosts.conf.

  • I've tried BarryVdh cors lib, I also created my own CORS middleware, nada.

Flow:

in web.php routes:

Route::get('/', function () {
    return view('welcome');
});

in welcome.blade I pass the csrf in both meta:

  <meta name="csrf-token" content="{{ csrf_token() }}">

and script:

<script>
    window.Laravel = <?php echo json_encode([
        'csrfToken' => csrf_token(),
    ]); ?>
</script>

My Vue instance:

<div class="container" id="app">
    <coin-add-component></coin-add-component>
</div>

and in my component I have the following hook:

mounted(){
    this.axios.get('https://api.coinmarketcap.com/v2/listings/')
        .then(response => {
            console.log(response.data);
        })
        .catch(e => {
            this.errors.push(e)
        })
}

Your help is appreciated,

Bud


Solution

The url you are trying to consume can't be used in crossdomain with javascript because it doesn't provide a response header of type "Access-Control-Allow-Origin". In this case, if you have no control on the API server you are forced to use other unconventional ways because all modern browsers will block any requests to that site if the domain doesn't match with yours.

You have 2 alternative to solve this problem:

  1. Use a proxy with your same domain of yours to redirect all calls to that server
  2. Make ajax calls to your server and then make your server communicate directly with the api server using for example curl


Answered By - Andrea Mauro
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Sunday, January 23, 2022

[FIXED] React + PHP API throws CORS preflight error

 January 23, 2022     api, cors, fetch, php, reactjs     No comments   

Issue

I am trying to call a PHP API running on localhost:8000 from a React app running on localhost:3000. After many tries I am still getting "CORS Preflight Did Not Succeed" error.

Sent from the React app: Sent from the app

Sent from the devtools: Sent from the devtools

My API has following headers:

if (@$_SERVER['HTTP_ORIGIN']) {
  header("Origin: http://localhost:8000");
  header("Access-Control-Allow-Origin: *");
  header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
  header('Access-Control-Max-Age: 1000');
  header('Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept');
} 

I call the API with fetch like this (but it somehow sends empty request body):

let inputData:object = {email, password}
fetch("http://localhost:8000/data/login", {
  method: "POST",
  headers: {
    "Content-Type": "application/json",
  },
  body: JSON.stringify(inputData)
})
.then(response => {
  console.log(response)
})
.catch(error => {
  console.log(error)
})

The strange thing is that the requests are working normally when sent directly from the browser devtools (2nd screenshot) or API clients like Insomnia:

Sent from an API client


Solution

Problem

Your first screenshot indicates that the response to the preflight request has status code 404. However, a necessary condition for CORS preflight to succeed is an ok status (i.e. a status in the range 2xx). See the relevant section (3.2.3) of the Fetch standard:

A successful HTTP response, i.e., one where the server developer intends to share it, to a CORS request can use any status, as long as it includes the headers stated above with values matching up with the request.

A successful HTTP response to a CORS-preflight request is similar, except it is restricted to an ok status, e.g., 200 or 204.

(my emphasis)

Solution

Make sure your server responds with a 2xx status to preflight requests that are meant to succeed.


Additional remarks

  1. Allowing the Origin header is never necessary, simply because it's set by the user agent. You can drop Origin from the value of the Access-Control-Allow-Headers response header.
  2. Why you're setting an Origin header in the response is unclear... Origin is a request header. You should be able to drop that header("Origin: http://localhost:8000"); line.
  3. Instead of "manually" implementing CORS (which is error-prone), you should consider using a proven CORS middleware.


Answered By - jub0bs
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Tuesday, January 11, 2022

[FIXED] API call to my Symfony 5 app with debug mode disabled returns CORS error

 January 11, 2022     api, cors, nginx, php, symfony     No comments   

Issue

I have this problem with my Symfony 5 app which serves as my API. I am making requests to my Symfony app from another app on the same domain and different subdomain.

Everything is fine when debug mode is set to true APP_DEBUG = 1 in my Symfony app. However if I disable debug mode APP_DEBUG = 0, then my requests from the other app cause CORS errors:

Access to XMLHttpRequest at 'https://api.mamacita365.com/api/getmeals' 
from origin 'https://app.mamacita365.com' has been blocked by CORS policy: 
No 'Access-Control-Allow-Origin' header is present on the requested resource.

I am using nelmio/cors-bundle - here's nelmio_cors.yaml:

nelmio_cors:
    defaults:
        origin_regex: true
        allow_credentials: true
        allow_origin: ['https://api.mamacita365.com', 'https://app.mamacita365.com']
        allow_methods: ['GET', 'OPTIONS', 'POST', 'PUT', 'PATCH', 'DELETE']
        allow_headers: ['Content-Type', 'Authorization']
        expose_headers: ['Link']
        max_age: 3600
    paths:
        '^/': null

Here's .env.local.php:

<?php

// This file was generated by running "composer dump-env prod"

return array (
  'APP_ENV' => 'prod',
  'APP_DEBUG' => 0, // if equals 0 then CORS error, if equals 1 then OK
  // ...
);

Solution

Clear the cache manually (/var/cache/prod folder) or via command php bin/console cache:clear --env=prod



Answered By - DVN-Anakin
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Wednesday, January 5, 2022

[FIXED] Laravel 5.1 API Enable Cors

 January 05, 2022     api, cors, laravel, laravel-5.1, php     No comments   

Issue

I've looked for some ways to enable cors on laravel 5.1 specifically, I have found some libs like:

https://github.com/neomerx/cors-illuminate

https://github.com/barryvdh/laravel-cors

but none of them has a implementation tutorial specifically to Laravel 5.1, I tried to config but It doesn't work.

If someone already implemented CORS on laravel 5.1 I would be grateful for the help...


Solution

Here is my CORS middleware:

<?php namespace App\Http\Middleware;

use Closure;

class CORS {

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {

        header("Access-Control-Allow-Origin: *");

        // ALLOW OPTIONS METHOD
        $headers = [
            'Access-Control-Allow-Methods'=> 'POST, GET, OPTIONS, PUT, DELETE',
            'Access-Control-Allow-Headers'=> 'Content-Type, X-Auth-Token, Origin'
        ];
        if($request->getMethod() == "OPTIONS") {
            // The client-side application can set only headers allowed in Access-Control-Allow-Headers
            return Response::make('OK', 200, $headers);
        }

        $response = $next($request);
        foreach($headers as $key => $value)
            $response->header($key, $value);
        return $response;
    }

}

To use CORS middleware you have to register it first in your app\Http\Kernel.php file like this:

protected $routeMiddleware = [
        //other middlewares
        'cors' => 'App\Http\Middleware\CORS',
    ];

Then you can use it in your routes

Route::get('example', array('middleware' => 'cors', 'uses' => 'ExampleController@dummy'));
Edit: In Laravel ^8.0 you have to import the namespace of the controller and use the class like this:
use App\Http\Controllers\ExampleController;

Route::get('example', [ExampleController::class, 'dummy'])->middleware('cors');


Answered By - Alex Kyriakidis
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Tuesday, January 4, 2022

[FIXED] Getting Cors error in Laravel on some system

 January 04, 2022     cors, laravel, laravel-5     No comments   

Issue

I hosted laravel (Laravel Framework 8.68.0) and angular application on two different domains, Sometime the same code works properly but sometimes it is throwing this error :

Access to XMLHttpRequest at from origin has been blocked by CORS policy Response to preflight request does'nt pass access control check : No Access Control Allow Origin header is present on the requested resource

Cors Middleware :

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;

class CORS
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next)
    {
        $response = $next($request);
        $response->header('Access-Control-Allow-Origin', '*')->header('Access-Control-Allow-Headers', 'Content-type, X-Auth-Token, Authorization, Origin');
        return $response;
    }
}

Kernel.php

   <?php

namespace App\Http;

use Illuminate\Foundation\Http\Kernel as HttpKernel;

class Kernel extends HttpKernel
{
    /**
     * The application's global HTTP middleware stack.
     *
     * These middleware are run during every request to your application.
     *
     * @var array
     */
    protected $middleware = [
        // \App\Http\Middleware\TrustHosts::class,
        \App\Http\Middleware\CORS::class,
        \App\Http\Middleware\TrustProxies::class,
        //\Fruitcake\Cors\HandleCors::class,
        \App\Http\Middleware\PreventRequestsDuringMaintenance::class,
        \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
        \App\Http\Middleware\TrimStrings::class,
        \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
        
    ];

    /**
     * The application's route middleware groups.
     *
     * @var array
     */
    protected $middlewareGroups = [
        'web' => [
            \App\Http\Middleware\EncryptCookies::class,
            \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
            \Illuminate\Session\Middleware\StartSession::class,
            // \Illuminate\Session\Middleware\AuthenticateSession::class,
            \Illuminate\View\Middleware\ShareErrorsFromSession::class,
            \App\Http\Middleware\VerifyCsrfToken::class,
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
        ],

        'api' => [
            // \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
            'throttle:api',
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
        ],
    ];

    /**
     * The application's route middleware.
     *
     * These middleware may be assigned to groups or used individually.
     *
     * @var array
     */
    protected $routeMiddleware = [
        'auth' => \App\Http\Middleware\Authenticate::class,
        'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
        'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
        'can' => \Illuminate\Auth\Middleware\Authorize::class,
        'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
        'password.confirm' => \Illuminate\Auth\Middleware\RequirePassword::class,
        'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
        'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
        'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
        //'guest' => \App\Http\Middleware\CORS::class,
        //'cors' => \App\Http\Middleware\CORS::class,
    ];
}

api.php

Route::group(['middleware' => ['api'],'prefix' => 'auth'], function ($router) {
    Route::post('/login', [AuthController::class, 'login']);
    Route::post('/register', [AuthController::class, 'register']);
    Route::post('/logout', [AuthController::class, 'logout']);
    Route::post('/refresh', [AuthController::class, 'refresh']);
    Route::get('/user-profile', [AuthController::class, 'userProfile']);    
});

cors.php

return [

    /*
    |--------------------------------------------------------------------------
    | Cross-Origin Resource Sharing (CORS) Configuration
    |--------------------------------------------------------------------------
    |
    | Here you may configure your settings for cross-origin resource sharing
    | or "CORS". This determines what cross-origin operations may execute
    | in web browsers. You are free to adjust these settings as needed.
    |
    | To learn more: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
    |
    */

    'paths' => ['api/*', 'sanctum/csrf-cookie'],

    'allowed_methods' => ['*'],

    'allowed_origins' => ['*'],

    'allowed_origins_patterns' => [],

    'allowed_headers' => ['*'],

    'exposed_headers' => [],

    'max_age' => 0,

    'supports_credentials' => false,

];

Route Service Provider :

<?php

namespace App\Providers;

use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Support\Facades\Route;

class RouteServiceProvider extends ServiceProvider
{
    /**
     * The path to the "home" route for your application.
     *
     * This is used by Laravel authentication to redirect users after login.
     *
     * @var string
     */
    public const HOME = '/home';

    /**
     * The controller namespace for the application.
     *
     * When present, controller route declarations will automatically be prefixed with this namespace.
     *
     * @var string|null
     */
    // protected $namespace = 'App\\Http\\Controllers';

    /**
     * Define your route model bindings, pattern filters, etc.
     *
     * @return void
     */
    public function boot()
    {
        $this->configureRateLimiting();

        $this->routes(function () {
            Route::prefix('api')
                ->middleware('api')
                ->namespace($this->namespace)
                ->group(base_path('routes/api.php'));

            Route::middleware('web')
                ->namespace($this->namespace)
                ->group(base_path('routes/web.php'));
        });
    }

    /**
     * Configure the rate limiters for the application.
     *
     * @return void
     */
    protected function configureRateLimiting()
    {
        RateLimiter::for('api', function (Request $request) {
            return Limit::perMinute(60)->by(optional($request->user())->id ?: $request->ip());
        });
    }
}

Any solution is highly appreciated

Thanks.


Solution

in addition to your defined Cors middleware, another Cors middleware has registered in the Global Middlewares : \Fruitcake\Cors\HandleCors::class


    /**
     * The application's global HTTP middleware stack.
     *
     * These middleware are run during every request to your application.
     *
     * @var array
     */
    protected $middleware = [
        // \App\Http\Middleware\TrustHosts::class,
        \App\Http\Middleware\TrustProxies::class,
/* comment this out*/
 //       \Fruitcake\Cors\HandleCors::class,
        \App\Http\Middleware\PreventRequestsDuringMaintenance::class,
        \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
        \App\Http\Middleware\TrimStrings::class,
        \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
    ];

you have forgotten the Access-Control-Allow-Methods header for your customized Cors.

        $response
->header('Access-Control-Allow-Origin', '*')
->header('Access-Control-Allow-Headers', 'Content-type, X-Auth-Token, Authorization, Origin')
->header('Access-Control-Allow-Methods','POST, GET, OPTIONS');


Answered By - Abilogos
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Monday, January 3, 2022

[FIXED] No 'Access-Control-Allow-Origin' header - Laravel

 January 03, 2022     cors, laravel, laravel-5, php     No comments   

Issue

XMLHttpRequest cannot load http://myapi/api/rating. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8104' is therefore not allowed access. The response had HTTP status code 403.

I can't figure out why I can't make CORS requests. I've install the middleware here, added it to the global http kernel, but it still doesn't work. Tried to create a custom middleware given stackoverflow suggestions but that also did not work. Also tried adding a Route group. Lastly, I tried setting the response headers manually in the request action. I'm really stuck - help is appreciated!

See for code: https://gist.github.com/KerryRitter/0d7ababb7b9eb8d54f0ae55add9704a1


Solution

If you are using Laravel 5.5 & Laravel 5.x and facing same problem like No 'Access-Control-Allow-Origin' header is present on the requested resource. Just use following package and config your system.

Step 1:

composer require barryvdh/laravel-cors

Step 2

You also need to add Cors\ServiceProvider to your config/app.php providers array:

FruitCake\Cors\CorsServiceProvider::class,

To allow CORS for all your routes, add the HandleCors middleware in the $middleware property of app/Http/Kernel.php class:

For global uses:

protected $middleware = [
    // ...
    \Fruitcake\Cors\HandleCors::class,
];

For middleware uses:

protected $middlewareGroups = [
   'web' => [
       // ...
   ],

   'api' => [
        // ...
        \Fruitcake\Cors\HandleCors::class,
    ],
];

Step 3

Once your installation completed run below command to publish the vendor files.

php artisan vendor:publish --provider="Fruitcake\Cors\ServiceProvider"

Hope this answer helps someone facing the same problem as myself.



Answered By - Rahul Hirve
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Older Posts Home
View mobile version

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
All Comments
Atom
All Comments

Copyright © PHPFixing