I'm writing a very common topic, but I am desperate, wasted two days trying to make this work.
I'm on Chrome, trying to make my first Login/Register app and at the time of sending the data to the backend, i get the following error:
XMLHttpRequest cannot load http://192.168.1.133:8100/api/login. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8100' is therefore not allowed access. The response had HTTP status code 500.
I am making a POST request from AngularJS like follows:
$scope.data = "UserName"; // for example
$scope.register = function() {
var withAjax = $http.post('http://192.168.1.133/api/register', $scope.data);
withAjax
.success(function(answer){
console.log(answer.message);
})
.error(function(answer) {
console.log("error");
});
}
])
And the Laravel API backend is simple, just return 'Correct'.
public function login (Request $request) {
$inputArray = $request->all();
return response()->json(["message" => "Login: All Correct"]);
}
In my front-end app I alowed all kind connections with:
<allow-navigation href="http://*/*" />
<allow-navigation href="*" />
<access origin="*"/>
In PHP I tried all. Disabled CSFR token for API, and installed properly "barryvdh/laravel-cors" and configured cors file like follows:
return [
'supportsCredentials' => false,
'allowedOrigins' => ['*'],
'allowedHeaders' => ['*'],
'allowedMethods' => ['*'], // ex: ['GET', 'POST', 'PUT', 'DELETE']
'exposedHeaders' => [],
];
When I can make, sending data back and forth easy process, I will care about protection. Now I decided to open 'all' to make it straightforward.
I'm crazy about this, lost two days just trying to solve this.
Any clue would be of help.
Thank you!
Try this plugin for Chrome, might help you. CORS
Related
Laravel sanctum has been a bit of a headache for me as i have spent hours trying to figure out why sanctum/csrf-cookie route returns no content. initially the same route return 404 not found but after adding 'prefix' => 'api/sanctum' config/sanctum.php it seems to work except that it outputs nothing and no cookie is set in my browser.
Here are some of my codes
.env
SANCTUM_STATEFUL_DOMAINS=localhost:8080
SPA_URL=http://localhost:8080
SESSION_DOMAIN=localhost
--config/cors.php
'paths' => [
'api/*',
'login',
'logout',
'register',
'user/password',
'forgot-password',
'reset-password',
'sanctum/csrf-cookie',
'user/profile-information',
'email/verification-notification',
],
'allowed_methods' => ['*'],
'allowed_origins' => ['*'],
'allowed_origins_patterns' => [],
'allowed_headers' => ['*'],
'exposed_headers' => [],
'max_age' => 0,
'supports_credentials' => true,
axios
export const authClient = axios.create({
baseURL: process.env.VUE_APP_API_URL,
withCredentials: true, // required to handle the CSRF token
});
and having done all of that, if i tried to generate a token using
axios.get('/sanctum/csrf-cookie').then(response => {
// Login...
});
i get 204 no content response
i have also added the api middleware in kernel.php as instructed in the doucmentation but still wont set the cookie. and when i try to make request to another route protected by sanctum i 419 token mismatch.
i have also run a fresh installation of laravel, php artisan optimize, cleared my brower history, checked the endpoints in postman but still thesame 204 and 419 exceptions
I was struggling with the same issue for days and then founded a way that worked.
so :
The '/sanctum/csrf-cookie' route return a 204 response when successfull, the then you have to send your post request with credentials. i used to get a 419 reponse status.
so after followed laravel docs here is what i added :
SPA
make sure you set the withCredentials header to true
API
.env
SESSION_DRIVER=cookie
SESSION_DOMAIN='.localhost'
SANCTUM_STATEFUL_DOMAINS='localhost,127.0.0.1'
.kernel.php
add in your middleware array : \Illuminate\Session\Middleware\StartSession::class
Hey I don't know whether you've found the answer or not but that request meant to have empty response body. Your CSRF token is available in the header of the response ;D
From HTTP Specification:
The HTTP 204 No Content success status response code indicates that a request has succeeded, but that the client doesn't need to navigate away from its current page. This might be used, for example, when implementing "save and continue editing" functionality for a wiki site.
According to specification 204 is the exptected response from server.
You can insert in bootstrap.js file
import axios from 'axios';
window._ = _;
window.axios = axios;
window.axios.defaults.baseURL = "/api/";
window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
I am installing the old project, which is made by Nuxt.js (frontend) and Laravel (backend) on my local.
Access to XMLHttpRequest at 'http://localhost:8000/api/user' from origin 'http://127.0.0.1:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.
This is the issue that I faced to run the project.
Frontend configuration for the request(nuxt nuxt.config.js).
user: {
url: '/api/user',
method: 'get',
propertyName: false,
withCredentials: true,
headers: {
X-Requested-With': 'XMLHttpRequest',
Content-Type': 'application/json'
}
}
Backend configuration (Laravel config/cors.php)
'paths' => ['api/*'],
'allowed_methods' => ['*'],
'allowed_origins' => ['*'],
'allowed_origins_patterns' => [],
'allowed_headers' => ['*'],
'exposed_headers' => [],
'max_age' => 0,
'supports_credentials' => true,
I tried to find the solution by googling but I didn't find the correct solution.
withCredetials is true
CORS: credentials mode is 'include'
The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'
So, I want someone to help me in this field.
Try this way in your laravel app:
php artisan serve --host YOUR_LOCAL_IP
YOUR_LOCAL_IP is your ip that can access with ifconfig command in linux and ipconfig in windows.
Finally you should request to YOUR_LOCAL_IP:PORT/api
I have a laravel application setup and I'm configuring a Discord auth system.
I have sent & requested authorization & recieved a confirmation code back.
When I try to exchange the code for an access token I'm receiving a 400 bad request and I'm not sure why.
I'm new to laravel and can't seem to find any sort of error that may help to pin point the problem.
Controller function that discord redirects after authorization
public function exchange(Request $request) {
//exchange discord code for access_token
$code = Request::get('code',false);
$params = array(
'grant_type' => 'authorization_code',
'client_id' => env('CLIENT_ID'),
'client_secret' => env('OAUTH2_CLIENT_SECRET'),
'redirect_uri' => Request::root().'/discord/return',
'scope' => 'identify guilds guilds.join',
'code' => $code
);
$access_token = Http::withOptions([
'debug' => true,
'headers' => [
'Accept' => 'application/json',
'Content-Type' => 'application/x-www-form-urlencoded'
],
'json' => $params
])->post('https://discordapp.com/api/oauth2/token');
dd($access_token);
return redirect()->route('return.discord',['token' => $access_token->access_token]);
}
I've dumped out $params and all the data is pulling in as it should.
Guzzle dumps this:
[CONNECT] [FAILURE] severity: "2" message: "HTTP/1.1 400 Bad Request " message_code: "400" [MIME_TYPE_IS] message: "application/json" [FILE_SIZE_IS] message: "Content-Length: 26" bytes_max: "26" [PROGRESS] bytes_max: "26"
I know that 400 bad request means an issue with the data being sent along, but I can't figure out what I'm doing that's not producing the correct result. The documentation states the required content type which I have set, so I'm really scratching my head here.
Any help would be much appreciated.
Here's the Discord API documentation:
https://discord.com/developers/docs/topics/oauth2#authorization-code-grant
To anyone looking for an answer...
The "invalid grant" error is due to an issue with the Discord API and non-standard requests. I could not get the Laravel HTTP class request to work for exchanging the access token. Instead, I used native php cURL within Laravel.
As for the issue with receiving '400 bad request', that was due to using incorrect function withOptions() as oppossed to asJson()->withHeaders(). Thanks #Zachary Craig!
However, I could not use this in the end due to the problem described above.
If any others find a better solution, let me know :)!
For all who have the same problem.
The solution is to use ->asForm() before the post. This changes the handling of the data from json to form_params. This way the Discord API accepts the parameters.
return Http::asForm()->post($this->endpoint.'/oauth2/token', $data);
I know it's a known issue but I've tried almost everything and I'm still stuck on this. I have a simple project structured like this:
[Client] => [Gateway] => [API]
Laravel 6 Lumen 6 Lumen 6
localhost:8000 localhost:8001 localhost:8002
Since I'm just started working on this project only to prove if this works I've disabled all auth stuff.
On my API I have a folder within public called uploads (Basically in http://localhost:8002/uploads/audio.amr) where I have 1 audio file (.amr) and I'm trying to play it from a client view.
Since html can't play .amr files, I had to use a plugin. And I'm using this one BenzAMRRecorder.
[Client side]
I make an ajax petition to get the url of the audio file. The client through guzzle connects with the gateway and the gateway also does it with the API and I successfully got the url http://localhost:8002/uploads/audio.amr.
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
url : 'client/get_url_audio',
type : 'GET',
data : {
},
dataType:'json',
success : function(data) {
/** Here's the way to play the file */
var amr = new BenzAMRRecorder();
amr.initWithUrl(data['url']).then(function() {
amr.play();
});
},
});
I successfully got the url but when the BenzAMRRecorder try to access to the url http://localhost:8002/uploads/audio.amr I got this error:
The error:
Access to XMLHttpRequest at 'http://localhost:8002/uploads/audio.amr' from origin 'http://localhost:8000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
I've read a lot of ways to fix this and I added a CorsMiddleware on the API with a handle function as follows:
public function handle($request, Closure $next)
{
$headers = [
'Access-Control-Allow-Origin' => '*',
'Access-Control-Allow-Methods' => 'POST, GET, OPTIONS, PUT, DELETE',
'Access-Control-Allow-Credentials' => 'true',
'Access-Control-Max-Age' => '86400',
'Access-Control-Allow-Headers' => 'Content-Type, Authorization, X-Requested-With'
];
if ($request->isMethod('OPTIONS'))
{
return response()->json('{"method":"OPTIONS"}', 200, $headers);
}
$response = $next($request);
foreach($headers as $key => $value)
{
$response->header($key, $value);
}
return $response;
}
And then on bootstrap/app.php added
$app->middleware([
App\Http\Middleware\Cors::class
]);
But I'm still getting the same error. The thing I thought is that, when the method amr.initWithUrl(data['url']) access to the API folder, it doesn't go to middleware and try to access directly to the folders without passing by the middleware but I don't know why. Can someone help me to solve this problem?
EDIT: I also tried with github.com/barryvdh/laravel-cors
Add the following in the .htaccess file from the server which holds the resource you are trying to access:
Header Set Access-Control-Allow-Origin "*"
I don't know if it works in Lumen, but for Laravel, I've had a lot of success using this neomerx/cors package.
You probably missed the header X-CSRF-TOKEN from your CORS middleware?
$headers = [
....
// You will need to add ALL headers sent from your client
'Access-Control-Allow-Headers' => 'Content-Type, Authorization, X-Requested-With, X-CSRF-TOKEN'
];
CORS Access to XMLHttpRequest at X from origin has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.
Hi, I am struggling to resolve my problems with CORS denying interaction of my Vue component with an external API with axios since it returns this error. I've tried both using Barryvdh's Cors header support and making a middleware and custom route. It simply won't work. Everything that has been mentioned in README.md in Barryvdh's repo has been done and unfortunately, this problem won't get resolved by any means necessary.
Here is the code, even though I don't think there's need to show since it's exactly the same as mentioned in the repo;
inside Kernel.php:
protected $middleware = [
\Barryvdh\Cors\HandleCors::class,
inside app.php (providers array):
Barryvdh\Cors\ServiceProvider::class,
config/cors.php:
'supportsCredentials' => false,
'allowedOrigins' => ['*'],
'allowedHeaders' => ['*'],
'allowedMethods' => ['*'], // ex: ['GET', 'POST', 'PUT', 'DELETE']
'exposedHeaders' => [],
'maxAge' => 0,
Here's the axios get call (I've replaced my token with 'TOKEN')
methods: {
loadWeatherData: function() {
axios.get( 'http://api.openweathermap.org/data/2.5/weather?q=London&mode=json&units=metric&appid=TOKEN' )
.then( function( response ) {
console.log( 'radi' );
}).catch( errors => {
console.log( errors+' ne radi');
});
}
},
I've composer dump-ed, nothing affected resolving the problem.
Is there something I am doing wrong and are there any solutions for this problem? Thanks in advance!
The problem here seems to be that axios likes to send its own default headers, and these don't pass the preflight check for your external request. To fix this, you will need to remove the offending headers.
I was able to recreate your error, and also to bypass the CORS issue using the code below.
let url = 'https://api.openweathermap.org/data/2.5/weather?q=London&mode=json&units=metric&appid=TOKEN';
// create a new instance so we don't delete the headers for other requests
let instance = axios.create();
// delete headers if existing
delete instance.defaults.headers.common['Accept'];
delete instance.defaults.headers.common['X-Requested-With'];
delete instance.defaults.headers.common['X-CSRF-TOKEN'];
// use the new axios instance to make your get request
instance.get(url)
.then(function(response) {
console.log(response);
}).catch( errors => {
console.log(errors + ' ne radi');
});
Hope this helps and good luck!
You can add into TrustHosts.php Middleware without doing anything extra. Read more from here https://stackoverflow.com/a/70361284/2612926