Vue js axios get request error - Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present - vue.js

I have done a simple get request using axios as follows
axios
.get('my api',{
withCredentials: true,
headers:{
'Authorization': 'token'
},
params:{
id:this.$route.params.id,
identity:this.$route.params.identity
}
}
And in the server side i added my local host ip and all to the allowed domains
http://localhost:8080
and the below things are my cors config
'Origin' => static::allowedDomains(),
'Access-Control-Request-Method' => ['POST','GET','OPTIONS'],
'Access-Control-Allow-Credentials' => true,
'Access-Control-Max-Age' => 3600,
'Access-Control-Allow-Headers' => ["Content-Type", "Authorization", "Access-Control-Allow-Methods", "Access-Control-Request-Headers"],
But i am still getting the error
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.
The auth token is not getting on the server i think.When i try to disable the token , then it is working.So the token is making the issue.How can i solve this.Thanks in advance

Finally i found the answer.It was an issue of using cors along with authentication.I just added my cors filters above the authentication like below.Before it was below the authentication
public function behaviors()
{
$behaviors = parent::behaviors();
unset($behaviors['authenticator']);
$behaviors['corsFilter']=[
'class' => \yii\filters\Cors::className(),
'cors' => [
'Origin'=> ['http://localhost:8080'],
'Access-Control-Allow-Credentials' => true,
'Access-Control-Allow-Headers' => ['Authorization'],
],
];
$behaviors['authenticator'] = [
'class' => JwtHttpBearerAuth::class,
];
return $behaviors;
}

Related

Access blocked by CORS policy No 'Access-Control-Allow-Origin' header is present on the requested resource

Laravel 9.19
Livewire 2.10
Filament 2.0
masbug/flysystem-google-drive-ext 2.2
I am trying to using google drive as a filesystems storage .. every thing works fine so i can store files and open it .. except that the filament can not fetch the stored file and the console log gives me an error
filesystems.php
'google' => [
'driver' => 'google',
'clientId' => "xxxxxxxxxxxx.apps.googleusercontent.com",
'clientSecret' => "xxxxxxxxxxxxxxxxxxxxx",
'refreshToken' => "xxxxxxxxxxxxxxxxxxxxxx",
'folderId' => env('GOOGLE_DRIVE_FOLDER_ID', null),
],
config/cors.php
<?php
return [
'paths' => ['api/*'], //try ['api/*', 'oauth/*'] , [] and ['*'] Nothing work
'allowed_methods' => ['*'],
'allowed_origins' => ['*'],
'allowed_origins_patterns' => [], //try ['*'] Not working
'allowed_headers' => ['*'],
'exposed_headers' => [],
'max_age' => 0,
'supports_credentials' => false, //try true Not working
];
ComplaintResource.php
public static function form(Form $form): Form
{
return $form
->schema([
Section::make('')
->schema([
//.........
FileUpload::make('reply_pdf')
->disk('google')
->acceptedFileTypes(['application/pdf']),
//.......
])->columns(3)
]);
}
the filament input keeps showing loading indicator
console.log
I am trying to make a middleware to solve this .. but nothing happen
Middleware/Cors.php
public function handle(Request $request, Closure $next)
{
$response = $next($request);
$response->headers->set('Access-Control-Allow-Origin', '*');
$response->headers->set('Access-Control-Allow-Methods', 'POST, GET, OPTIONS, PUT, DELETE');
$response->headers->set('Access-Control-Allow-Headers', 'Content-Type, Accept, Authorization, X-Requested-With, Application');
return $response;
}
I tried to add the next code to .htaccess file .. but it didn't work also
.htaccess
<IfModule mod_headers.c>
Header set Access-Control-Allow-Origin "*"
</IfModule>
I am run php artisan config:clear and php artisan cache:clear .. not working
The only thing that worked after install CORS Unblock extension to Chrome browser and enable Access-Control-Allow-Origin from it!

Browser fails to set cookies even with Set-Cookie response header

I am trying to get my Express backend to set a site-wide cookie on my NextJS frontend, each of which is running on separate virtual machines. The relevant backend and frontend configurations are:
In the frontend, I initate the following HTTP request:
fetch('http://192.168.1.<Express virtual machine>:3000/service', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({...}),
credentials: 'include'
}).then(res => res.json()).then(data => {console.log(data)});
In the backend, the following Express application is running with a global CORS middleware configured:
app.use(cors({origin: 'http://192.168.1.<Frontend virtual machine>:3000', credentials: true}));
app.post('/service', (req, res) => {
res.cookie('token', token, {
secure: false,
httpOnly: false,
sameSite: 'none'
});
res.json({...});
});
Upon initiating the HTTP request to /service, the Cookies section of my frontend application in the Storage (Firefox) or Application (Chrome) tab shows that there are no cookies set. However, in the network tab, the Cookies tab on my HTTP request shows that there is both a response cookie and a request cookie. The response cookie has path property set to '/' suggesting that it should have been set site-wide.

How to set CORS header in cloudflare workers?

I'm using cloudflare workers to create a reverse proxy but I can't use it to embed on main domain cause it gives CORS error:
Access to image at 'https://example.workers.dev/96384873_p0.png' from origin 'https://example.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
here's the code in workers
addEventListener("fetch", event => {
let url = new URL(event.request.url);
url.hostname = "i.pximg.net";
let request = new Request(url, event.request);
event.respondWith(
fetch(request, {
headers: {
'Referer': 'https://www.pixiv.net/',
'User-Agent': 'Cloudflare Workers'
}
})
);
});
How can I fix the CORS error?
You should read up on CORS to understand why you are receiving this error, then the fix should be straightforward (setting additional headers) - https://web.dev/cross-origin-resource-sharing/

POST Fetch request returns: grant_type was not specified

I had working code for fetching a access token with oauth, then I did a expo eject and now when I try to POST my auth code to get the access_token i receive response.
.then((auth_code) => {
let my_headers = new Headers()
my_headers.append('Authorization', `Basic ${base64_auth}`)
my_headers.append('Content-Type', 'application/x-www-form-urlencoded')
my_headers.append('Access-Control-Allow-Origin', '*')
my_headers.append('grant_type', 'authorization_code')
let urlencoded = new URLSearchParams()
urlencoded.append('code', auth_code)
urlencoded.append('grant_type', 'authorization_code') // <-- GRANT_TYPE HERE
let request_options = {
method: 'POST',
headers: my_headers,
body: urlencoded,
mode: 'cors'
}
console.log(request_options) // <--- OUTPUT BELOW
let url_with_params = `https://${url}/oauth/token/`
fetch(url_with_params, request_options)
.then((response) => response.json())
.then((json) => console.log(json)) // <--- OUTPUT BELOW
.then((json) => helpers.set_session_object('oauth_object', json))
.finally(() => set_loading(false))
.catch((error) => console.log('error', error))
})
.catch((error) => console.error(error))
console.log(request_options) outputs the following:
{method: "POST", headers: Headers, body: URLSearchParams, mode: "cors"}
body: URLSearchParams {_searchParams: Array(1)}
headers: Headers
map:
access-control-allow-origin: "*"
authorization: "Basic YXdheTprTkwpUmtWc2lWM2ppaCk3WDlmZXp3aSk="
content-type: "application/x-www-form-urlencoded"
grant_type: "authorization_code"
method: "POST"
mode: "cors"
and the json response outputs:
{"error": "invalid_request", "error_description": "The grant type was not specified in the request"}
Any idea why this is happening? I obviously have the grant_type declared right?
Looking at this I can see a couple of things that may not be quite right:
Remove the trailing backslash at the end of the OAuth token URL
Include a redirect_uri field, which is required in Authorization Code Grant messages
I suspect the first issue above is causing a redirect so that the POST to https://url/oauth/token/ becomes a GET to https://url/oauth/token.
Some similar issues are described in this post, and above all else I would aim to ensure that you can use an HTTP Proxy tool to view messages, which will make you much more productive at diagnosing this type of issue in future.
PROXY MOBILE SETUP
If it helps, my blog has some posts on proxy setup details:
Android HTTP Proxy Setup
iOS HTTP Proxy Setup

No 'Access-Control-Allow-Origin' header is present on the requested resource with CORS module enabled

I am trying to get CORS working on my AWS Lambda server using Serverless. Right now I have two sub-domains (api.site.co and app.site.co).
In my app.js file on Express, I have installed CORS and enabled it like such:
app.use(
cors({
origin: 'https://app.site.co',
optionsSuccessStatus: 200,
}),
);
app.options('*', cors());
And then using the Axios module in React, I make this call:
axios
.post('/users/register', user)
.then(res => history.push('/login'))
.catch((err) => {
dispatch({
type: GET_ERRORS,
error: err.response.data,
});
});
Also, in my app.js file for the client app:
axios.defaults.baseURL = 'https://api.site.co';
When submitting any request, I receive this error:
Access to XMLHttpRequest at 'https://api.site.co/users/register' from origin 'https://app.site.co' 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.
So, far I have also tried changing my CORS configuration to:
app.use(cors());
app.options('*', cors());
But I am still getting the same error.
Any suggestions on how to address this?
Looks like there is a typo:
https://app.site.co/users/register => https://api.site.co/users/register
You're making a request to https://api.site.co but your configuration specifies https://app.site.co
This was a problem with the AWS Lambda Serverless setup. I needed to add
functions:
app:
handler: app.handler
events:
- http:
path: /
method: any
cors:
origin: 'https://app.site.co'
- http:
path: '{proxy+}'
method: any
cors:
origin: 'https://app.site.co'
So that it would allow CORS requests when proxying to the Express middleware.