I am using Laravel sanctum in my project with angular as frontend. Getting unauthenticated from the second api request. Please let me know where am I going wrong
Frontend-> 127.0.0.1:4200
Backend-> localhost:8888
.env config
SESSION_DOMAIN=localhost
SANCTUM_STATEFUL_DOMAINS=127.0.0.1
Added middleware auth:sanctum to the routes group in api.php
Ref: https://prnt.sc/rm9ejy
For anyone having an Unauthenticated error, please ensure you follow these steps.
Send a GET request to /sanctum/csrf-cookie
Send a post request to web route /login to get authenticated
After this step, you will be successfully authenticated by auth:sanctum middleware in the WEB route or any resource route that needs CRSF token present.
[Why did this work]
Sending a GET request(empty request) to /sanctum/csrf-cookie enables laravel to send the fresh set cookies command to your browser to set a fresh CRSF token which can be found in your cookies. Axios and most library send this fresh token as part of headers X-CSRF-TOKEN by default, for regular ajax request, please include them explicitly in your headers or in form _token, else your SPA will still hit the 419(token expired) error
Other things to be aware of:
Ensure your SESSION_DOMAIN is set to localhost
SANCTUM_STATEFUL_DOMAIN is set to your sub domain/SPA with the port e.g localhost:8000
For the original question please ensure you maintain same domain. I mean use localhost for both. And set SANCTUM_STATEFUL_DOMAIN = localhost:4200
Edited
Also set SESSION_DRIVER
Add your domains, for example
my API is running on localhost:8000 my client is running on localhost:3000 so my env setting looks like below
SANCTUM_STATEFUL_DOMAINS=localhost:8000,localhost:3000
also, add your session domain
SESSION_DOMAIN=localhost
Have you checked your Kernel.php? app/Http/Kernel.php
Make sure you uncomment \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class, coz by default it is being commented
'api' => [
\Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
'throttle:api',
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
Two days of pain and despair to arrive at this conclusion: the Bearer token was not attached to the request, and that was because of my .htaccess configuration.
If you, like me, are not able to authenticate via API token, try to add this line on your .htaccess file in the public directory in your Laravel project:
RewriteRule ^ - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
Right after RewriteEngine On directive.
CREDITS: Laravel not detecting auth token sent in the header and JWT package
From the screenshot you shared I see your domain is localhost and not 127.0.01, just do:
SANCTUM_STATEFUL_DOMAINS=localhost
For anyone using Laravel Homestead, use your actual domain.
SANCTUM_STATEFUL_DOMAINS=homestead.test
Which version are you running? Since V2.4.0 you need to specify the port:
SANCTUM_STATEFUL_DOMAINS=localhost:4200
See this issue for more info.
The sanctum stateful domains require the port number as well.
e.g. SANCTUM_STATEFUL_DOMAINS=127.0.0.1:4200
Although in your case your screenshot shows it should be SANCTUM_STATEFUL_DOMAINS=127.0.0.1:4201
Late in the game but just to help those that keep looking for this solution, most of the answers here have some truth, just have to put them together to make it work:
ENV file: SESSION_DOMAIN=localhost (or whatever your domains is)
in config->sanctum.php->stateful (if not already there): Sanctum::currentApplicationUrlWithPort()
in app/Http/Kernel.php API add as very first (this is important) : \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
in app/http/kernel API remove if there: \Illuminate\Session\Middleware\StartSession::class,
add to your api routes middleware: auth:sanctum
Also worth checking the guard settings under config->sanctum.php
that should do.
I had the same solution as Marco, adding the rewrite rule to my htaccess in public fixed it.
RewriteRule ^ - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
FYI I am hosting this on Auzre Web App Service (linux), if anyone else is doing that.
check if you had changed your guard in past. goto config/auth.php check if your provider model is same as your user model (or the model you using) for authentication.
in my case i was using different guard and provider.
In case you have problems when going into production and/or have more than one subdomains and also use https don't forget that the port is 443 instead of the usual 80.
E.g.:
SANCTUM_STATEFUL_DOMAINS=*.example.com:443
SESSION_DOMAIN=.example.com
Lost days trying to figure out why the laravel, the spa or the android app were taking turns to fail, but never working all at the same time, until found that solution.
This worked for me. The solution is adding this to .htaccess of root folder (not only inside the public folder)
# Handle Authorization Header
RewriteCond %{HTTP:Authorization} .
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
I have developed application in Angular 7 and APIs in Laravel 5.7.
For CORS issue, I have also installed barryvdh/laravel-cors package in Laravel and its working fine on local.
But when I deployed these both applications on Godaddy single hosting, that is Starter Linux Hosting with cPanel
Angular app in main directory public_html
Laravel APIs in public_html/api directory which points to
public_html/api/public
APIs are not working and I am seeing this error
Access to XMLHttpRequest at 'http://api.example.com/api/documentations?page=1' from origin 'http://example.com' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: Redirect is not allowed for a preflight request
I have seen lot of answers on stackoverflow and on other sources, nothing seems to be working for me.
I tried adding headers to .htaccess file
<IfModule mod_headers.c>
Header set Access-Control-Allow-Origin "*"
</IfModule>
As well as directly to index.php but with no luck.
header('Access-Control-Allow-Origin', '*')
Any idea or help is highly appreciated. Thanks in advance.
Redirect is not allowed for a preflight request
Since you have a HTTP to HTTPS redirect in place, and your API calls are trying to access http://api.example.com/api/documentations?page=1, they're going to fail, because (as the message states) you can't redirect a CORS preflight.
Update your code to make the API calls over HTTPS.
Thank you #ceejayoz for your valuable comments and answer. I am able to find the issue
I am having two .htaccess files. For main domain, one at
public_html/.htaccess
and another for subdomain at
public_html/api/public/.htaccess
The one at public_html/.htaccess having this line to protect the files inside the public_html/api directory from root access of main domain
RedirectMatch 403 ^/api/.*$
When I commented/removed this line, APIs started working but files inside public_html/api directory were not secure.
Then to secure the files, I created one more file at public_html/api/.htaccess and added these lines
RewriteEngine On
RewriteRule !^public/ - [F,NC]
And I achieved both: APIs are working and files inside public_html/api are secured.
I am working on a website, let say the website name is "https://website" (which is built on wordpress) in which I am getting the following error on console:
Uncaught DOMException: Blocked a frame with origin "https://website" from accessing a cross-origin frame.
at contents (https://website/wp-admin/load-scripts.php?c=1&load%5B%5D=jquery-core,jquery-migrate,jquery-ui-core,jquery-ui-widget,jquery-ui-mouse,jquery-ui-sortable,utils,underscore,wp-util,backbone,&load%5B%5D=moxiejs,plupload&ver=4.9.8:2:26921)
at Function.map (https://website/wp-admin/load-scripts.php?c=1&load%5B%5D=jquery-core,jquery-migrate,jquery-ui-core,jquery-ui-widget,jquery-ui-mouse,jquery-ui-sortable,utils,underscore,wp-util,backbone,&load%5B%5D=moxiejs,plupload&ver=4.9.8:2:3613)
at a.fn.init.n.fn.(anonymous function) [as contents] (https://website/wp-admin/load-scripts.php?c=1&load%5B%5D=jquery-core,jquery-migrate,jquery-ui-core,jquery-ui-widget,jquery-ui-mouse,jquery-ui-sortable,utils,underscore,wp-util,backbone,&load%5B%5D=moxiejs,plupload&ver=4.9.8:2:27001)
at b (https://website/wp-admin/load-scripts.php?c=1&load%5B%5D=postbox,thickbox,hoverIntent,common,admin-bar,wp-a11y,updates,plugin-install,svg-painter,heartbeat,wp-auth-check,shortcode,wp-ba&load%5B%5D=ckbone,media-models,wp-plupload,wp-mediaelement,wp-api-request,media-views,media-editor,media-audiovideo,mce-view,imgareaselect,&load%5B%5D=image-edit&ver=4.9.8:347:103)
at HTMLBodyElement.<anonymous> (https://website/wp-admin/load-scripts.php?c=1&load%5B%5D=postbox,thickbox,hoverIntent,common,admin-bar,wp-a11y,updates,plugin-install,svg-painter,heartbeat,wp-auth-check,shortcode,wp-ba&load%5B%5D=ckbone,media-models,wp-plupload,wp-mediaelement,wp-api-request,media-views,media-editor,media-audiovideo,mce-view,imgareaselect,&load%5B%5D=image-edit&ver=4.9.8:347:1306)
at HTMLBodyElement.dispatch (https://website/wp-admin/load-scripts.php?c=1&load%5B%5D=jquery-core,jquery-migrate,jquery-ui-core,jquery-ui-widget,jquery-ui-mouse,jquery-ui-sortable,utils,underscore,wp-util,backbone,&load%5B%5D=moxiejs,plupload&ver=4.9.8:3:12444)
at HTMLBodyElement.r.handle (https://website/wp-admin/load-scripts.php?c=1&load%5B%5D=jquery-core,jquery-migrate,jquery-ui-core,jquery-ui-widget,jquery-ui-mouse,jquery-ui-sortable,utils,underscore,wp-util,backbone,&load%5B%5D=moxiejs,plupload&ver=4.9.8:3:9173)
at Object.trigger (https://website/wp-admin/load-scripts.php?c=1&load%5B%5D=jquery-core,jquery-migrate,jquery-ui-core,jquery-ui-widget,jquery-ui-mouse,jquery-ui-sortable,utils,underscore,wp-util,backbone,&load%5B%5D=moxiejs,plupload&ver=4.9.8:3:11573)
at Object.a.event.trigger (https://website/wp-admin/load-scripts.php?c=1&load%5B%5D=jquery-core,jquery-migrate,jquery-ui-core,jquery-ui-widget,jquery-ui-mouse,jquery-ui-sortable,utils,underscore,wp-util,backbone,&load%5B%5D=moxiejs,plupload&ver=4.9.8:9:8275)
at HTMLDivElement.<anonymous> (https://website/wp-admin/load-scripts.php?c=1&load%5B%5D=jquery-core,jquery-migrate,jquery-ui-core,jquery-ui-widget,jquery-ui-mouse,jquery-ui-sortable,utils,underscore,wp-util,backbone,&load%5B%5D=moxiejs,plupload&ver=4.9.8:3:18991)
The above error is generated by clicking View Details section of wordpress plugins (as shown below):
This error seems to exist in every single wordpress plugins but it works when I open in a new tab but it doesn't work when I open in the same window.
Problem Statement:
I am wondering which file I need to modify in wordpress in order to solve this error. This error seems to exist in every wordpress plugins. As mentioned, it works in a new tab but fails to work in the same page.
I have a feeling I have to make some changes in the following file by seeing the error above (load-scripts.php, as the error is generated in that file) but not sure what line I need to add in order to make it work.
https://website/wp-admin/load-scripts.php
Something bad has happend to your WordPress admin interface.
The first thing to notice is that the error you have described is a well known problem as you may have already noticed: SecurityError: Blocked a frame with origin from accessing a cross-origin frame
Look at the first answer there:
You can't access an with different origin using JavaScript,
it would be a huge security flaw if you could do it. For the
same-origin policy browsers block scripts trying to access a frame
with a different origin.
Protocol, hostname and port must be the same of your domain, if you
want to access a frame.
The second thing to notice is what the "View details" button in the WordPress admin interface does: It opens a ThickBox containing and iframe which is showing remote contents quite often within an IFrame. How this works is ecactly described here: https://codex.wordpress.org/Javascript_Reference/ThickBox
load-scripts.php is an important WordPress core file loaded in the admin which is used to load JavaScript files without having to embed each of them. Those JavaScript files are usually added to your WordPress admin with the admin_enqueue_scripts() function (https://codex.wordpress.org/Plugin_API/Action_Reference/admin_enqueue_scripts).
As your problem is quite uncommon and the "View details" button for Plugins works almost everytime there are only two possibilities:
1. The "View Details" IFrame is usually loaded from the same location where your WordPress is - therefore you might have a problem such that the browser wants to load it from a different host
This happens if you have some misconfiguration within your WordPress installation and Thickbox tries to get an IFrame from a host which the Browser thinks is another host. Configure WordPress correctly.
2. You have a badly programmed plugin or theme which is injecting a script causing this problem
Solution: Deactivate your theme and all your plugins one-by-one and see if the error still exists. This way you can find out the modification which causes the problem and maybe do a bug request to the plugin developers then.
It is almost 100% sure that a single plugin, theme or misconfiguration is causing this problem.
For posterity, chances are your X-Frame-Options have either been set to deny by the server or a configuration was appended by another plugin, but the blocked frame issue may happen when your server has not been configured correctly or was configured with strict policies to prevent any sort of access to cross-origin frames. Since every plugin is affected when viewing the Details link, my answer coincides with what #Blackbam has explained regarding how it functions by bringing up a thickbox and uses an i-frame when explaining why they all don't seem to appear.
I am wondering which file I need to modify in WordPress in order to
solve this error. This error seems to exist in every wordpress
plugins. As mentioned, it works in a new tab but fails to work in the
same page.
So, for this particular case I don't believe it's necessarily a WordPress issue but a hosting server configuration and, depending on how much access you have to the server or wherever you're building the website, will determine what you can do to solve this error or whether or not you'll need to contact support to help you resolve it.
(Since this answer is simply added for posterity, please excuse the present tense references used as I realize it's been 3 years since this was asked)
Solutions:
There are two options that may work for you, and will vary depending on your server and your user access.
Solution 1: Adding permissions by modifying the .htaccess file
If your webhosting server is running on Apache or other supported web server, you can try adding the lines below to the .htaccess file:
<ifModule mod_headers.c>
Header set Strict-Transport-Security "max-age=31536000" env=HTTPS
Header always set X-Frame-Options "sameorigin"
Header setifempty Referrer-Policy: same-origin
</ifModule>
For syntax, you can refer to to this page. But as another option, instead of setting X-Frame-Options to "sameorigin" you can also specify a particular domain so as to preserve the security feature if preferred, such as:
Header always append X-Frame-Options "ALLOW-FROM website.com/*"
And replacing "website.com/*" with the domain you would like to permit, noting the space between ALLOW-FROM and the URL as further explained here. If you have other plugins installed that have modified your .htaccess file, be sure to place this entry above any Wordpress created entry as the .htaccess file is loaded in order and also note that it may not be supported in all browsers. Now, depending on the server security policies, if this doesn't work, then you'll have to move on to the next solution.
Solution 2: Modify your server configuration
Though I'm only including instructions for an Apache server from here as reference, this page includes configurations for Nginx, IIS, HAProxy, and Express as well. A full explanation can be found here if you have access to WHM and/or are running virtual servers and will require root access.
Log into the web server and look for the following file:
/etc/apache2/conf/httpd.conf
# or you can also create a new file named 'include.conf' if it
# doesn't already exist
/etc/apache2/conf.d/userdata/{USERNAME}/{DOMAIN-NAME}/include.conf
If the file exists, you can either comment out the line if it's set to DENY to disable the restriction or add the line below to the newly created configuration file:
<ifModule mod_headers.c>
Header set Strict-Transport-Security "max-age=31536000" env=HTTPS
Header always set X-Frame-Options "sameorigin"
</ifModule>
You'll then need to rebuild the configuration and restart the Apache server.
You can rebuild by running the command
/usr/local/cpanel/scripts/rebuildhttpdconf
Then restart with
/usr/local/cpanel/scripts/restartsrv_httpd
Without the same-origin setting, even though Wordpress is installed on the server, the jquery requests are being blocked as part of preventing any embedding of content from other sites as well. Read more about Secure Headers from OWASP
I am trying to login with ajax to an API and I get this error:
XMLHttpRequest cannot load. The 'Access-Control-Allow-Origin' header
has a value that is not equal to the supplied origin. Origin
'http://localhost' is therefore not allowed access.
I read all about this error, all over the internet, and I've tried all the solutions I could find online. I modified the .htaccess and apache httpd configuration file according to the CORS instructions here: http://enable-cors.org/server_apache.html
Access-Control-Allow-Origin: *
Nothing seems to be working. I'd really appreciate if you guys can help me out with this. Thank you!
You have to set Access-Control-Allow-Origin header to * or specified value http://localhost
You can do this through:
1- Your code
2- .htaccess file
3- Server config (restart web server required)
Here is the link that show how to do it on apache
http://access-control-allow-origin-guide.com/enable-cors-on-apache-linux/
As added browser security, unless the API allows cross-browser origins in the the return responses header there is no way around this.
The browsers are blocking it, there is a plugin to allow for chrome but it is not realistic to depend on browser plugin to allow end user requests,
Try and reach out to the API provider and see if they can look into updating the header in the response.
It is a CORS issue:
https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
i use htaccess file for load JSON data in different hosting, and its works but
it have to put inside the public html root of our web hosting for example
uploading .htaccess into --> (https://freehostingsomewhere.com/)
then inside .htaccess
<FilesMatch "\.(ttf|otf|eot|woff|jpg|png|jpeg|gif|js|json|html|css)$">
<IfModule mod_headers.c>
Header set Access-Control-Allow-Origin "http://localhost"
</IfModule>
</FilesMatch>
in here i use http://localhost to development and it works,
maybe if i have another web host just change it into that url, i will try it later (it can, i already try it) :p
this is just for more clear explanation
cheers :p
Are your requests using either cookies or authorization by any chance?
Check on your ajax call on the client side if you're configuring it to be done "with credentials"
.withCredentials = true;
If yes, the wildcard(*) will not work and you'll need to provide the exact host as the value for Access-Control-Allow-Origin.
Refer to this stack overflow answer or Mozilla Documentation on CORS