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

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!

Related

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

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;
}

Guzzle 6 is following redirects on local docker server, but not on production server

I am using Guzzle 6 Http Client to scrape web pages and analyze them from SEO perspective, however interesting thing is, that Guzzle does not follow redirects at all, when being used in production, but code is exatly the same. Here is the snippet I am using to request page and track redirects.
$onRedirect = function (RequestInterface $request, ResponseInterface $response, UriInterface $uri): void {
$this->totalRedirects++;
};
$response = $this->httpClient->request('GET', $url, [
'allow_redirects' => [
'max' => self::MAX_REDIRECTS,
'referer' => true,
'track_redirects' => true,
'on_redirect' => $onRedirect
],
'headers' => [
'User-Agent' => self::USER_AGENT
],
'http_errors' => true
]);
$redirectUrls = $response->getHeader('X-Guzzle-Redirect-History');
$redirectStatuses = $response->getHeader('X-Guzzle-Redirect-Status-History');
foreach ($redirectUrls as $key => $redirectUrl) {
$this->responses[] = new HttpResponse($redirectUrl, $redirectStatuses[$key]);
}
//Save last successful response
$this->responses[] = new HttpResponse($url, $response->getStatusCode());
My redirect middleware is not triggered at all, using this in production and it returns only "307", while in docker I get "307" and "200". This have been tested using samaritans page - (https://www.samaritans.org/)
Both Production and docker are using PHP 7.2 and Guzzle 6

Disable Shibboleth-Omniauth Debug Mode

I have Installed Gitlab EE with Apache2 and Shibboleth. Configuration is working fine and I get all data I need for authentification I think. I set debug to false in gitlab.rb but I always get the folwing message with the sso callback. Am I missing something? Where do I have to set debug to false?
!!!!! This message is generated by omniauth-shibboleth. To remove it set :debug to false. !!!!!
HTTP_ACCEPT: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8
HTTP_ACCEPT_ENCODING: gzip, deflate
HTTP_ACCEPT_LANGUAGE: de-DE,de;q=0.9,en-US;q=0.8,en;q=0.7,it;q=0.6,fr;q=0.5
HTTP_AFFILIATION: ....
...
This is part of my gitlab Config:
gitlab_rails['omniauth_providers'] = [
{
"name" => 'shibboleth',
"args" => {
"debug" => "false",
"shib_session_id_field" => "HTTP_SHIB_SESSION_ID",
"shib_application_id_field" => "HTTP_SHIB_APPLICATION_ID",
"uid_field" => 'HTTP_UID',
"name_field" => 'HTTP_DISPLAYNAME',
"info_fields" => { "email" => 'HTTP_EMAIL'}
}
}
]

Silex security doesn't ask name and password

I am using Silex and apache. I want to disallow access for anonymous users to localhost/admin page. I read docs, docs of SimpleUserProvider and create the following index.php:
<?php
require_once __DIR__.'/../vendor/autoload.php';
use Silex\Provider;
use Symfony\Component\HttpFoundation\Request;
$app = new Silex\Application();
$app->register(new Provider\SecurityServiceProvider());
$app->register(new Provider\SessionServiceProvider());
$app->register(new Provider\TwigServiceProvider(), [
"twig.path" => __DIR__.'/../views'
]);
$app['debug'] = true;
$app['security.firewalls'] = array(
'default' => array(
'pattern' => '^/',
),
'secured' => array(
'pattern' => '^/admin/',
'form' => array('login_path' => '/login', 'check_path' => '/login_check'),
'users' => array(
'admin' => array('ROLE_ADMIN', '5FZ2Z8QIkA7UTZ4BYkoC+GsReLf569mSKDsfods6LYQ8t+a8EW9oaircfMpmaLbPBh4FOBiiFyLfuZmTSUwzZg=='),
'daria' => array('ROLE_USER', '5FZ2Z8QIkA7UTZ4BYkoC+GsReLf569mSKDsfods6LYQ8t+a8EW9oaircfMpmaLbPBh4FOBiiFyLfuZmTSUwzZg=='),
),
),
);
$app['security.access_rules'] = array(
array('^/admin', 'ROLE_ADMIN', 'https'),
array('^.*$', 'ROLE_USER'),
);
$app -> boot();
$app->get('/', function () {
return 'Hello from Silex container.';
});
$app->get('/admin/', function() {
return "Admin page";
});
$app->get('/login', function(Request $request) use ($app) {
return "Login page";
});
$app->get('/logout/', function() {
return "Logout page";
});
$app->get('/admin/login_check/', function() {
return "Admin login check page";
});
$app->run();
As Symfony 2 docs says, if I request to localhost/admin, I should see input fields for pass and login in alert.
So when I go to 'localhost' all are right, I see correct message. But when I go to 'localhost/admin' I expect that browser will ask with alert my login and password. But it doesn't happens, I get 'ERR_CONNECTION_REFUSED Site localhost disallow connection'. In apache log I have 301 http code. Is it normal behavior that browser doesn't ask login/password with alert? If yes, what should I add to code to change that behavior?
P.S. I know that hardcoded login and password are terrible, but I am just started Silex and it doesn't matter.
I think that you get ERR_CONNECTION_REFUSED error because of redirect to https. Try to remove this redirect by changing array('^/admin', 'ROLE_ADMIN', 'https'), to array('^/admin', 'ROLE_ADMIN'),.
Remove default section from firewalls. This section is first, catches all requests and doesn't require authorization.
If you want standard alert with user/password prompt, specify http entry point instead of form.
$app['security.firewalls'] = array(
'secured' => array(
'pattern' => '^/admin/',
'http' => array(),
'users' => array(
'admin' => array('ROLE_ADMIN', '...'),
'daria' => array('ROLE_USER', '...'),
),
),
);

Zend 2 and auth configuration routing

I'm working curently on a Zend2 project where there is an authentifaction system for the whole website, it was fine until we had to develop a module which is an public web service.
I would like to know if it's possible to allow users to access to a specific module/routing of Zend 2 ?
The Zend\Authentication\Adapter\Http provides an easy way for Apache like authentication in Zend Framework 2 applications.
It comes with two implementations Basic and Digest HTTP Authentication, which can be combined with two sub components - the class itself or a FileResolver. We are going to use the FileResolver to read the stored credentials and compare them to the submitted values.
First thing first. There are few important things to know.
Create a folder with name auth in MODULE_NAME/config/. Inside that folder create two files basic.txt and digest.txt. The file formats are smillar to Apache .htpasswd files.
Basic - <username>:<realm>:<credentials>, here credentials should be written in clear text, e.g.: basic:authentication:plaintextpassword.
Digest - <username>:<realm>:<credentials>, where <credentials> is the md5 hash of all 3 parts, e.g.: digest:authentication:dc45122ef294d83e84a8b5a3a6c5356b
In the same module, where we have just created our auth folder, open module.config.php file and place this code.
The code tells us which authentication schemes we accept, the realm (must be the same as the realm in the basic/digest.txt files, digest_domains (only when we use digest authentication) is the URL(s) where we want to apply the same valid information, nonce_timeout sets the number of seconds for which the nonce is valid.
/**
* Used for basic authentication
*/
'authentication_basic' => [
'adapter' => [
'config' => [
'accept_schemes' => 'basic',
'realm' => 'authentication',
'nonce_timeout' => 3600,
],
'basic' => __DIR__.'/auth/basic.txt',
],
],
/**
* Used for digest authentication
*/
'authentication_digest' => [
'adapter' => [
'config' => [
'accept_schemes' => 'digest',
'realm' => 'authentication',
'digest_domains' => '/learn-zf2-authentication/digest',
'nonce_timeout' => 3600,
],
'digest' => __DIR__.'/auth/digest.txt',
],
]
LearnZF2Authentication\Factory\BasicAuthenticationAdapterFactory
$config = $serviceLocator->get('Config');
$authConfig = $config['authentication_basic']['adapter'];
$authAdapter = new HttpAdapter($authConfig['config']);
$basic = new FileResolver();
$basic->setFile($authConfig['basic']);
$authAdapter->setBasicResolver($basic);
return $authAdapter;
LearnZF2Authentication\Factory\DigestAuthenticationAdapterFactory
$config = $serviceLocator->get('Config');
$authConfig = $config['authentication_digest']['adapter'];
$authAdapter = new HttpAdapter($authConfig['config']);
$digest = new FileResolver();
$digest->setFile($authConfig['digest']);
$authAdapter->setDigestResolver($digest);
return $authAdapter;
These are the codes we use to pass the authentication information
Module.php
/**
* #var MvcEvent $e
*/
$request = $e->getRequest();
$response = $e->getResponse();
$view = $e->getApplication()->getMvcEvent()->getViewModel();
$sm = $e->getApplication()->getServiceManager();
$authAdapter = $sm->get('LearnZF2Authentication\BasicAuthenticationAdapter');
/**
* Not HTTP? Stop!
*/
if (!($request instanceof Http\Request && $response instanceof Http\Response)) {
return;
}
/**
* Call the factory class and try to authenticate
*/
if ($e->getRouteMatch()->getParam('action') == 'digest') {
$authAdapter = $sm->get('LearnZF2Authentication\DigestAuthenticationAdapter');
}
$authAdapter->setRequest($request);
$authAdapter->setResponse($response);
if($e->getRouteMatch()->getParam('action') == 'basic' || $e->getRouteMatch()->getParam('action') == 'digest') {
$result = $authAdapter->authenticate();
/**
* Pass the information to the view and see what we got
*/
if ($result->isValid()) {
return $view->identity = $result->getIdentity();
} else {
/**
* Create a log function or just use the one from LearnZF2.
* Also make sure to redirect to another page, 404 for example
*/
foreach ($result->getMessages() as $msg) {
return $view->authProblem = $msg;
}
}
}
This is the code we use to pass the authentication information
One last important thing to note is that you must include a special header called Authorization n your request, replace :
RewriteRule ^(.*)$ %{ENV:BASE}index.php [NC,L]
with
PHP compiled as CGI does not support apache_response_headers function, but we need this header in order to do basic HTTP authtentication when running with CGI or FastCGI.
RewriteRule ^(.*)$ %{ENV:BASE}index.php [E=HTTP_AUTHORIZATION:% {HTTP:Authorization},L,NC]
and add in top of public/index.php
if (isset($_SERVER["REDIRECT_HTTP_AUTHORIZATION"])) {
$_SERVER["HTTP_AUTHORIZATION"] = $_SERVER["REDIRECT_HTTP_AUTHORIZATION"];
}
Some things to note. The auth folder as well the authentication code from module.config.php is best to be placed in your main config folder, where the global|local.php files are and excluded from commits.