CORS ORIGIN problem, In a Laravel project - laravel

I have a problem with cors origin in my laravel project, I created cors.php in middwares folder and I declare it in Kernel.php and app/Providers/RouteServiceProvider.php as well... I did everything to solve it in my Laravel project, even in folder config I added a file Cors.php
I'm now wondering if I have to add something in Nginx configuration or Apache configuration ?
I'm hosting my project in hostinger VPS, The version of linux is ubuntu 22.04.5 LTS
Thank you in advance.
Regards
Middlewares/Cors.php
<?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)
{
return $next($request)
->header('Access-Control-Allow-Origin', '*')
}
}
config/cors.php
<?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/*','web/*', 'sanctum/*'],
'allowed_methods' => ['*'],
'allowed_origins' => ['*'],
'allowed_origins_patterns' => ['*'],
'allowed_headers' => ['*'],
'exposed_headers' => ['*'],
'max_age' => 0,
'supports_credentials' => true
];
I added also this lines to Http/kernel.php
protected $routeMiddleware = [
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'auth.session' => \Illuminate\Session\Middleware\AuthenticateSession::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,
'cors' => \App\Http\Middleware\Cors::class, // added
];
I in console I have this message ( see pictures ):
and I have this message in console : Download the Vue Devtools extension for a better development experience:
https://github.com/vuejs/vue-devtools
post.js:42559 You are running Vue in development mode.
Make sure to turn on production mode when deploying for production.
See more tips at https://vuejs.org/guide/deployment.html
scrollspy.js:224 Uncaught TypeError: Cannot read properties of null (reading 'classList')
at An._activate (scrollspy.js:224:10)
at An._process (scrollspy.js:191:14)
at new An (scrollspy.js:80:10)
at bg_scripts.js:35:9
sb-forms-latest.js:5 Uncaught Error: GET_ELEMENTS: -> form[data-sb-form-api-token]
at e (sb-forms-latest.js:5:415)
at sb-forms-latest.js:5:3777
profile.js:32882 Error: Network Error
at createError (profile.js:872:15)
at XMLHttpRequest.handleError (profile.js:754:14)
127.0.0.1:8000/getMessages:1 Failed to load resource: net::ERR_CONNECTION_REFUSED
boxicons.min.css:1 Failed to load resource: the server responded with a status of 404 ()
[enter image description here][1]
[enter image description here][2]
[1]: https://i.stack.imgur.com/T9DhM.png
[2]: https://i.stack.imgur.com/7zXtW.png

are you Building an API with a SPA ?
and he will be better if you have some error just provide us.

No Problem, Create a new Middleware and put this line in it:
$response = $next($request);
$response->headers->set('Access-Control-Allow-Origin', '*');
$response->headers->set('Access-Control-Allow-Methods', '*');
$response->headers->set('Access-Control-Allow-Credentials', true);
$response->headers->set('Access-Control-Allow-Headers', 'X-Requested-With,Content-Type,X-Token-Auth,Authorization');
return $response;
and your problem will be solved
You Can check this repo for more details

Related

Receiving CORS policy error on every API request nuxtJS

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.
You may check if there's any abnormal response like die(...), dd(..) or exit.
These methods also may trigger cors error.
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

react native application returns 404 error

I am creating app in react native with laravel backend.So as I want to get api from laravel server so i run laravel with that command
php artisan serve --host=some-domain.test --port=anyPort
I create api like that way
Route::get('users','PostController#get_users');
function get_users()
{
return Response()->json(User::get(),200);
}
In react native I call that api in that way
constructor()
{
super();
this.state={
data :[]
}
}
componentDidMount()
{
this.callApi();
}
async callApi()
{
let data=await fetch(' http://192.168.1.1:8081/api/users') //same as where laravel server is running
let adata= await data.text();
this.setState({data:adata})
console.warn(data)
}
It returns me 404 error:development server returned response error code:404
but when i stop laravel server and refresh my app then start laravel server it return me that error
Possible unhandled promise rejection(id:0):
what should I do now ?
You are not handling your Promise right hence you get the Error. The way that Fetch should be used is something like this:
fetch('http://example.com/movies.json')
.then(response => response.json())
.then(data => console.log(data));
You can read more about it on the official Docs:
https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
If you want to set the State you would have to do it in the second .then() Call.
Also remeber to add a .catch(err => console.log(err)) to filter your errors.
I think you need to handle cors request
You can install this package
https://github.com/fruitcake/laravel-cors
To generate config file run following command
php artisan vendor:publish --tag="cors"
and then update in config/cors.php
<?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/*'],
'allowed_methods' => ['*'],
'allowed_origins' => ['*'],
'allowed_origins_patterns' => [],
'allowed_headers' => ['*'],
'exposed_headers' => [],
'max_age' => 0,
'supports_credentials' => false,
];
To allow CORS for all your routes, add the HandleCors middleware at the top of the $middleware property of app/Http/Kernel.php class:
protected $middleware = [
\Fruitcake\Cors\HandleCors::class,
// ...
];

Laravel 7 cors problem for nuxt with grouped prefix

New to nuxt and laravel 7 Route::group
Update opened an issue here:
https://github.com/fruitcake/laravel-cors/issues/487
My laravel and cors package versions:
- "fruitcake/laravel-cors": "^2.0",
- "laravel/framework": "^7.24",
My Api Routes
Route::group(['prefix' => 'auth', 'namespace' => 'Auth'], function () {
Route::post('signin', 'SignInController');
Route::get('me', 'MeController');
Route::post('signout', 'SignOutController');
});
Route::group(['prefix' => 'snippets', 'namespace' => 'Snippets'], function () {
Route::post('', 'SnippetController#store');
Route::get('{snippet:uuid}', 'SnippetController#show');
});
The auth route works but the snippet one doesn't work.
My cors is like this:
<?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/*', 'api/snippets', '*'],
'allowed_methods' => ['*'],
'allowed_origins' => ['http://localhost:3000'],
'allowed_origins_patterns' => ['*'],
'allowed_headers' => ['*'],
'exposed_headers' => [],
'max_age' => 0,
'supports_credentials' => false,
];
I also tried this
<?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/*'],
'allowed_methods' => ['*'],
'allowed_origins' => ['*'],
'allowed_origins_patterns' => ['*'],
'allowed_headers' => ['*'],
'exposed_headers' => [],
'max_age' => 0,
'supports_credentials' => false,
];
Before every retry, I used the php artisan config:cache command.
Cors error
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:8000/api/snippets. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).
This request http://localhost:8000/api/snippets/ works fine in postman but not in nuxt, I get the cors error.
Can someone tell me what is happening here?
Thanks
Using dd or any log function in laravel will affect the cors.
Here is a quote from the official site https://github.com/fruitcake/laravel-cors#echodie
Echo/die
If you echo(), dd(), die(), exit(), dump() etc in your code, you will break the Middleware flow. When an output is sent before headers, CORS cannot be added. When the scripts exits before the CORS middleware finished, CORS headers will not be added. Always return a proper response or throw an Exception.
This code will make it work:
public function store(Request $request)
{
$snippet = $request->user()->snippets()->create();
return fractal()
->item($snippet)
->transformWith(new SnippetTransformer)
->toArray();
}

Axios getting blocked by laravel 7 cors. No "access-control-allow-origin-header"

I've a backend app working with Laravel 7 and a frontend which works with VueJs. My Laravel app is running on laradock (nginx, postgres etc...) Using Postman the API (Laravel 7) works properly.
This API replies by dns or by ip. http://192.168.0.3:80/api/mobile or http://laraapi.com/api/mobile
Once I'm still developing the VueJs app I'm running it with "npm run serve" which provides two ways to access my app, first by localhost and the second one by IP address. Both of them running on port 8081.
When Axios consume the API which uses the GET verb, everything works fine. When Axios consumes a POST verb than a get error.
Access to XMLHttpRequest at 'http://larapi.com/api/mobile/startorder/' from origin 'http://192.168.0.3:8081' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
By default laravel 7 already have a pre-done configuration for CORS which is provided by "Fruitcake"
So my kernel.php is like that:
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,
];
Fruitcake was moved in to be the first one, the tip from another StackOverflow which didn't help anyway.
My cors configuration:
'paths' => ['*'],
'allowed_methods' => ['*'],
'allowed_origins' => ['*'],
'allowed_origins_patterns' => [],
'allowed_headers' => ['*'],
'exposed_headers' => false,
'max_age' => false,
'supports_credentials' => true,
See that supports_credentials and allowed_origins were changed. Anyway, changing allowed_origins to "*" does not work.
I've created another route file named "mobile" and I'm using this one instead of "api.php", the content is:
Route::group(['middleware' => 'auth:api'], function(){
Route::namespace('Mobile')->group(function () {
Route::post('startorder',
['as' => 'startorder', 'uses' => 'PRC\PurchaseController#startOrder']);
});
});
This new file was created because the idea is use api.php for another purpose.
I've tried already to set a proxy on VueJs side but unfortunately, the result was the same one.
Axios call
import { http } from "./config";
startOrder: (order, user, token) => {
var data = {
"order": order,
"user": user,
}
return http.post("startorder/",data, {
headers: {
Authorization: "Bearer " + token,
"Content-Type": "application/json",
},
withCredentials: true,
});
}
my config.js
import axios from "axios";
export const http = axios.create({
baseURL: "http://192.168.0.3:80/api/mobile/",
withCredentials: true
});
vue.config.js
module.exports = {
devServer: {
proxy: "http://192.168.0.3:80/api/mobile/",
open: process.platform === 'darwin',
host: '0.0.0.0',
port: 8081,
https: false,
hotOnly: false,
},
chainWebpack: config => {
config
.plugin('html')
.tap(args => {
args[0].title = 'LaraAPi'
return args
})
}
}
For sure something is missing but actually I don't know which side is wrong anymore after a lot of tries.
I would appreciate it a lot if someone would help with that issue.
if you use axios withCredentials = true you need to enable laravel cros.php file supports_credentials = true
for axios code example:
axios.get('/user?ID=12345', { withCredentials: true })
.then(function (response) {
// handle success
console.log(response);
})
.catch(function (error) {
// handle error
console.log(error);
})
.then(function () {
// always executed
});
for cros.php code example
[
'paths' => ['api/*', 'sanctum/csrf-cookie'],
'allowed_methods' => ['*'],
'allowed_origins' => ['*'],
'allowed_origins_patterns' => [],
'allowed_headers' => ['*'],
'exposed_headers' => [],
'max_age' => 0,
'supports_credentials' => true
]
I don't know about this '*' stuff. Remember, this is very bad practice in production!
Access to XMLHttpRequest at 'http://larapi.com/api/mobile/startorder/'
from origin 'http://192.168.0.3:8081' has been blocked by CORS policy:
No 'Access-Control-Allow-Origin' header is present on the requested
resource.
Try to put the failed origin inside cors.php:
'paths' => ['api/*'],
'allowed_origins' => ['http://192.168.0.3:8081', 'http://192.168.0.3:80', 'http://laraapi.com'],
All three origins above are allowed to make requests to this endpoint.
It's always recommended to create an environment variable to better control this type of configurations. If you make it work in development, it will automatically work in production too!
'paths' => ['api/*'],
'allowed_origins' => env('CORS_ALLOWED_ORIGINS'),
.env
CORS_ALLOWED_ORIGINS=http://192.168.0.3:8081,http://192.168.0.3:80,http://laraapi.com
Update your production .env file accordingly.
cors.php I strongly suggest you change paths
<?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' => ['*'],
'allowed_methods' => ['*'],
'allowed_origins' => ['*'],
'allowed_origins_patterns' => [],
'allowed_headers' => ['*'],
'exposed_headers' => false,
'max_age' => false,
'supports_credentials' => false,
];
Kernel.php
<?php
namespace App\Http;
use App\Http\Middleware\cors;
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\TrustProxies::class,
\App\Http\Middleware\CheckForMaintenanceMode::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' => [
'throttle:60,1',
\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,
'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,
'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,
];
}
mobile.php (similar to api.php)
<?php
header('Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token, Authorization, Accept,charset,boundary,Content-Length');
header('Access-Control-Allow-Origin: http://192.168.0.4:8081');
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/
Route::post('login', 'Mobile\Login\UserController#login');
Route::post('register', 'Mobile\Login\UserController#register');
Route::middleware('auth:api')->get('/user', function (Request $request) {
return $request->user();
});
VueJs Side
//const configureAPI = require('./src/server/configure')
module.exports = {
devServer: {
proxy: "http://192.168.0.4:80/api/mobile/",
open: process.platform === 'darwin',
host: '0.0.0.0',
port: 8081, // CHANGE YOUR PORT HERE!
https: false,
hotOnly: false,
}
}
config.js
import axios from "axios";
export const http = axios.create({
baseURL: "http://192.168.0.4:80/api/mobile/",
withCredentials: false
});
service.js (consumes the API)
start: (parameter, token) => {
var data = {
parameter: parameter,
user: user,
};
return http.post("start/", data, {
headers: {
Authorization: "Bearer " + token,
"Content-Type": "application/json",
},
withCredentials: false,
});
},
#Keith Gulbro I hope this helps you to fix that nightmare. Let me know if you need something else.
Folks, seems the issue has been solved at least for now.
I will keep looking for a better solution.
Below, the details how this was solved.
1- remove the \Fruitcake\Cors\HandleCors::class from protected middleware on kernel.php
2 - On the header of api routes file you must set those lines below:
header('Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token, Authorization, Accept,charset,boundary,Content-Length');
header('Access-Control-Allow-Origin: http://192.168.0.3:8081');
In my case, I removed the wildcard * and put my valid origin. The wildcard is insecure.
3 - I've changed my Axios post method to send withCredentials as false.
export default {
login: data => {
return http.post("login",data, {
headers: {
"Content-Type": "application/json",
},
withCredentials: false,
});
},
4 - Config and cache were cleared.
php artisan config:clear
php artisan cache:clear
Now the response header is fulfilled correctly and the Access-Control-Allow-Origin' error disappeared.
Anyway, might have a better solution using FruitCake, otherwise would make no sense at all to provide an inefficient package.
If someone has a better solution, please share it!
Thank's

Laravel and Amazon SES

I am setting up Amazon SES for the first time. Following the documentation on Laravel website I have installed a package and started to set up mail.
mail.php
<?php
return [
'driver' => env('MAIL_DRIVER', 'ses'),
'host' => env('MAIL_HOST', 'smtp.mailgun.org'),
'port' => env('MAIL_PORT', 587),
'from' => [
'address' => env('MAIL_FROM_ADDRESS', 'hello#example.com'),
'name' => env('MAIL_FROM_NAME', 'Example'),
],
'encryption' => env('MAIL_ENCRYPTION', 'tls'),
'username' => env('MAIL_USERNAME'),
'password' => env('MAIL_PASSWORD'),
'sendmail' => '/usr/sbin/sendmail -bs',
'markdown' => [
'theme' => 'default',
'paths' => [
resource_path('views/vendor/mail'),
],
],
];
services.php
'ses' => [
'key' => env('SES_KEY'),
'secret' => env('SES_SECRET'),
'region' => 'eu-west-1',
],
.env
MAIL_DRIVER=ses
SES_KEY=ASKFKGDRJ3
SES_SECRET=kdfsjjdsfjdfsjdfsj
MAIL_HOST=email.eu-west-1.amazonaws.com
MAIL_PORT=587
MAIL_USERNAME=null
MAIL_PASSWORD=null
MAIL_ENCRYPTION=null
Mail/WelcomeEmail.php
<?php
namespace App\Mail;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Queue\ShouldQueue;
class WelcomeEmail extends Mailable
{
use Queueable, SerializesModels;
/**
* Create a new message instance.
*
* #return void
*/
public function __construct()
{
//
}
/**
* Build the message.
*
* #return $this
*/
public function build()
{
return $this->from('test#gmail.com')
->view('emails.welcomeEmail');
}
}
welcomeEmail.blade.php
<p>This is a test email from test email address, let me know on slack if you receive it</p>
Controller:
public function map(Request $request)
{
Mail::to($request->user())->send(new WelcomeEmail());
return view('profile.map');
}
And error:
Error executing "SendRawEmail" on "https://email.eu-west-1.amazonaws.com"; AWS HTTP error: Client error: `POST https://email.eu-west-1.amazonaws.com` resulted in a `403 Forbidden` response:
<ErrorResponse xmlns="http://ses.amazonaws.com/doc/2010-12-01/">
<Error>
<Type>Sender</Type>
<Code>SignatureDo (truncated...)
SignatureDoesNotMatch (client): The request signature we calculated does not match the signature you provided. Check your AWS Secret Access Key and signing method. Consult the service documentation for details.
The Canonical String for this request should have been
'POST
/
aws-sdk-invocation-id:7a73507566587348bba7c543661be161
aws-sdk-retry:0/0
host:email.eu-west-1.amazonaws.com
x-amz-date:20170726T195108Z
aws-sdk-invocation-id;aws-sdk-retry;host;x-amz-date
7a1f353a7f93f014d66ee19fb4b9661a79fea8411d1f97af2799c0cc04dc57dc'
The String-to-Sign should have been
'AWS4-HMAC-SHA256
20170726T195108Z
20170726/eu-west-1/ses/aws4_request
c2422180627319d05721ed6a2dc3973f7a508c34e4b2f9699d0a7bbf0c56d6a8'
- <ErrorResponse xmlns="http://ses.amazonaws.com/doc/2010-12-01/">
<Error>
<Type>Sender</Type>
<Code>SignatureDoesNotMatch</Code>
<Message>The request signature we calculated does not match the signature you provided. Check your AWS Secret Access Key and signing method. Consult the service documentation for details.
The Canonical String for this request should have been
'POST
/
aws-sdk-invocation-id:7a73507566587348bba7c543661be161
aws-sdk-retry:0/0
host:email.eu-west-1.amazonaws.com
x-amz-date:20170726T195108Z
aws-sdk-invocation-id;aws-sdk-retry;host;x-amz-date
7a1f353a7f93f014d66ee19fb4b9661a79fea8411d1f97af2799c0cc04dc57dc'
The String-to-Sign should have been
'AWS4-HMAC-SHA256
20170726T195108Z
20170726/eu-west-1/ses/aws4_request
c2422180627319d05721ed6a2dc3973f7a508c34e4b2f9699d0a7bbf0c56d6a8'
</Message>
</Error>
<RequestId>c458f296-723b-11e7-a686-515a08ffcc2f</RequestId>
</ErrorResponse>
However, I am sure that SES_key and secret is correct, domain is verified, and email also, what am I missing?
Yes, it not says that the email I am sending to is not verified?
This means you're in the SES "sandbox".
http://docs.aws.amazon.com/ses/latest/DeveloperGuide/request-production-access.html
During development:
You can only send mail to the Amazon SES mailbox simulator and to verified email addresses and domains.
You can only send mail from verified email addresses and domains.
You can send a maximum of 200 messages per 24-hour period.
Amazon SES can accept a maximum of one message from your account per second.
Moving from sandbox to production (where you can send email to anyone) is easy enough - just fill out the form at https://aws.amazon.com/ses/extendedaccessrequest/.
it's means your in sandbox mode and in sandbox mode only verified email get maild so either move from sandbox to production or verify your mail for testing mail but at last you have to move in production

Resources