Following Google Lighthouse recommandations to get a faster response for my website, I'm using this trick to post-load fonts:
<link as="style"
href="https://fonts.googleapis.com/css2?family=Montserrat:wght#400;600;700&display=swap"
onload="this.onload=null;this.rel='stylesheet'"
rel="preload">
But it fails because of my strict CSP rules, and I don't know how to add a sha384 hash for this "onload" attribute :/
I tried to get the onload content hash like this:
echo "this.onload=null;this.rel='stylesheet'" | openssl dgst | openssl enc -base64 -A
Output: npWtxZLLH7z2/zORM47igyJ5eTYuOl9qxzn4A632S7yMmMKBDHhL5ZHC6eBSxc/C
Then I add it on CSP SRI list, and refresh, but it fails with:
Refused to execute inline event handler because it violates the
following Content Security Policy directive: "script-src
'strict-dynamic' '[...list of other SRI hashes...]'
sha384-npWtxZLLH7z2/zORM47igyJ5eTYuOl9qxzn4A632S7yMmMKBDHhL5ZHC6eBSxc/C
'unsafe-inline' http: https:". Note that 'unsafe-inline' is ignored if
either a hash or nonce value is present in the source list.
How to permit this inline "onload" little script without authorize all inline scripts ?
Why my SRI doesn't work when I add it ? :(
Thanks !
Why my SRI doesn't work when I add it ? :(
It's explained here on example of style-src directive. With the script-src situation the same.
How to permit this inline "onload" little script without authorize all
inline scripts ?
Move inline event handler of 'load' to a separate script like 'click' in this topic. Then it can be allowed by 'nonce-value' or 'sha256/sha384/sha512-value'.
Updated:
I wish to clarity changes to do (move inline handler to a separate script):
<link as="style" id="fonts"
href="https://fonts.googleapis.com/css2?family=Montserrat:wght#400;600;700&display=swap"
rel="preload">
<script nonce="sever_generated_value"> // if 'nonce-value' used.
// Or just calculate hash sha256 (or sha384/512) of this script
// and insert it into 'script-src' as 'sha256-calculated_value'
fonts.addEventListener("load", function() {
this.onload=null;
this.rel='stylesheet';
});
</script>
Such separate inline script can be allowed by 'nonce-value'/'hash-value'.
PS: Pls note that Content Security Policy does not support 'hash-value' via SRI for external style sheets. Is supported only for built-in <style>...</style>. For scripts the 'hash-value' is supported for both: buil-in <script>...</script> and external <script src='...' integrity='hash_here'>
Why am I getting this error in console?
Refused to execute script from
'https://www.googleapis.com/customsearch/v1?key=API_KEY&q=flower&searchType=image&fileType=jpg&imgSize=small&alt=json'
because its MIME type ('application/json') is not executable, and
strict MIME type checking is enabled.
In my case it was a file not found, I typed the path to the javascript file incorrectly.
You have a <script> element that is trying to load some external JavaScript.
The URL you have given it points to a JSON file and not a JavaScript program.
The server is correctly reporting that it is JSON so the browser is aborting with that error message instead of trying to execute the JSON as JavaScript (which would throw an error).
Odds are that the underlying reason for this is that you are trying to make an Ajax request, have hit a cross origin error and have tried to fix it by telling jQuery that you are using JSONP. This only works if the URL provides JSONP (which is a different subset of JavaScript), which this one doesn't.
The same URL with the additional query string parameter callback=the_name_of_your_callback_function does return JavaScript though.
This result is the first that pops-up in google, and is more broad than what's happening here. The following will apply to an express server:
I was trying to access resources from a nested folder.
Inside index.html i had
<script src="./script.js"></script>
The static route was mounted at :
app.use(express.static(__dirname));
But the script.js is located in the nested folder as in: js/myStaticApp/script.js
I just changed the static route to:
app.use(express.static(path.join(__dirname, "js")));
Now it works :)
Try to use express.static() if you are using Node.js.
You simply need to pass the name of the directory where you keep your static assets, to the express.static middleware to start serving the files directly. For example, if you keep your images, CSS, and JavaScript files in a directory named public, you can do as below −
i.e. : app.use(express.static('public'));
This approach resolved my issue.
In my case, I was working on legacy code
and I have this line of code
<script type="text/javascript" src="js/i18n.js.php"></script>
I was confused about how this supposed to work this code was calling PHP file not js
despite it was working on the live server
but I have this error on the stage sever
and the content type was
content-type: text/html; charset=UTF-8
even it is text/javascript in the script tag
and after I added
header('Content-Type: text/javascript');
at the beginning for file i18n.js.php
the error is fixed
After searching for a while I realized that this error in my Windows 10 64 bits was related to JavaScript. In order to see this go to your browser DevTools and confirm that first. In my case it shows an error like "MIME type ('application/javascript') is not executable".
If that is the case I've found a solution. Here's the deal:
Borrowing user "ilango100" on https://github.com/jupyterlab/jupyterlab/issues/6098:
I had the exact same issue a while ago. I think this issue is specific to Windows. It is due to the wrong MIME type being set in Windows registry for javascript files. I solved the issue by editing the Windows registry with correct content type:
regedit -> HKEY_LOCAL_MACHINE\Software\Classes -> You will see lot of folders for each file extension -> Just scroll down to ".js" registry and select it -> On the right, if the "Content Type" value is other than application/javascript, then this is causing the problem. Right click on Content Type and change the value to application/javascript
enter image description here
Try again in the browser."
After that I've realized that the error changes. It doesn't even open automatically in the browser anymore. PGAdmin, however, will be open on the side bar (close to the calendar/clock). By trying to open in the browser directly ("New PGAdmin 4 window...") it doesn't work either.
FINAL SOLUTION: click on "Copy server URL" and paste it on your browser. It worked for me!
EDIT: Copying server URL might not be necessary, as explained by Eric Mutta in the comment below.
I accidentally named the js file .min instead of .min.js ...
Python flask
On Windows, it uses data from the registry, so if the "Content Type" value in HKCR/.js is not set to the proper MIME type it can cause your problem.
Open regedit and go to the HKEY_CLASSES_ROOT make sure the key .js/Content Type has the value text/javascript
C:\>reg query HKCR\.js /v "Content Type"
HKEY_CLASSES_ROOT\.js
Content Type REG_SZ text/javascript
In my case (React app), just force cleaning the cache and it worked.
I had my web server returning:
Content-Type: application\javascript
and couldn't for the life of me figure out what was wrong. Then I realized I had the slash in the wrong direction. It should be:
Content-Type: application/javascript
In my case, while executing my typescript file,
I wrote:
<script src="./script.ts"></script>
Instead of:
<script src="./script.js"></script>
In my case Spring Security was looking for authentication before allowing calls to external libraries. I had a folder /dist/.. that I had added to the project, once I added the folder to the ignore list in my WebSecurityConfig class, it worked fine.
web.ignoring().antMatchers("/resources/**", "/static/**", "/css/**", "/js/**", "/images/**", "/error", "/dist/**");
Check for empty src in script tag.
In my case, i was dynamically populating src from script(php in my case), but in a particular case src remained empty, which caused this error. Out was something like this:
<script src=""></script> //empty src causes error
So instead of empty src in script tag, I removed the script tag all together.
Something like this:
if($src !== ''){
echo '<script src="'.$src.'"></script>';
}
You can use just Use type
or which you are using you choose that file type
My problem was that I have been putting the CSS files in the scripts definition area just above the end of the
Try to check the files spots within your pages
I am using SpringMVC+tomcat+React
#Anfuca's answer does not work for me(force cleaning the browser's cache)
I used Filter to forward specific url pattern to the React's index.html
public class FrontFilter extends HttpFilter {
#Override
protected void doFilter(HttpServletRequest req, HttpServletResponse res, FilterChain chain) throws IOException, ServletException {
boolean startsWithApi = requestURI.startsWith("/api/");
boolean isFrontendUri = requestURI.startsWith("/index.html");
if (!startsWithApi && !isFrontendUri) {
req.getRequestDispatcher("/index.html").forward(req, res);
}
super.doFilter(wrapped, res, chain);
}
}
There is no Spring Security problem bcs my filter executes before Spring Security's
but I still see the same error and find here
Then I realized that I forgot adding one more condition for JS and CSS:
boolean startsWithStatic = requestURI.startsWith(contextPath + "/static");
Add this to my if condition and problem solved, no more error with MIME type or ('text/html') with js and css
Root cause is that I incorrectly forward JS and CSS type to HTML type
I got the same error. I realized my app.js was in another folder. I just moved it into that folder where my index.html file is and it resolved.
In Angular Development try this
Add the code snippet as shown below to the entry html. i.e "index.html" in reactjs
<div id="wrapper"></div>
<base href="/" />
If you have a route on express such as:
app.get("*", (req, res) => {
...
});
Try to change it for something more specific:
app.get("/", (req, res) => {
...
});
For example.
Or else you just might find yourself recursively serving the same HTML template over and over...
In my case I had a symlink for the 404'd file and my Tomcat was not configured to allow symlinks.
I know that it is not likely to be the cause for most people, but if you are desperate, check this possibility just in case.
I hade same problem then i fixed like this
change "text/javascript"
to
type="application/json"
I solved my problem by adding just ${pageContext.request.contextPath} to my jsp path .
in stead of :
<script src="static/js/jquery-3.2.1.min.js"></script>
I set :
<script src="${pageContext.request.contextPath}/static/js/jquery-3.2.1.min.js"></script>
I'm trying to make a request with Content-Type x-www-form-urlencoded that works perfectly in postman but does not work in Azure Logic App I receive a Bad Request response for missing parameters, like I'd not send enything.
I'm using the Http action.
The body value is param1=value1¶m2=value2, but I tried other formats.
HTTP Method: POST
URI : https://xxx/oauth2/token
In Headers section, add the below content-type:
Content-Type: application/x-www-form-urlencoded
And in the Body, add:
grant_type=xxx&client_id=xxx&resource=xxx&client_secret=xxx
Try out the below solution . Its working for me .
concat(
'grant_type=',encodeUriComponent('authorization_code'),
'&client_id=',encodeUriComponent('xxx'),
'&client_secret=',encodeUriComponent('xxx'),
'&redirect_uri=',encodeUriComponent('xxx'),
'&scope=',encodeUriComponent('xxx'),
'&code=',encodeUriComponent(triggerOutputs()['relativePathParameters']['code'])).
Here code is dynamic parameter coming from the previous flow's query parameter.
NOTE : **Do not forget to specify in header as Content-Type ->>>> application/x-www-form-urlencoded**
Answering this one, as I needed to make a call like this myself, today.
As Assaf mentions above, the request indeed has to be urlEncoded and a lot of times you want to compose the actual message payload.
Also, make sure to add the Content-Type header in the HTTP action with value application/x-www-form-urlencoded
therefore, you can use the following code to combine variables that get urlEncoded:
concat('token=', **encodeUriComponent**(body('ApplicationToken')?['value']),'&user=', **encodeUriComponent**(body('UserToken')?['value']),'&title=Stock+Order+Status+Changed&message=to+do')
When using the concat function (in composing), the curly braces are not needed.
First of all the body needs to be:
{ param1=value1¶m2=value2 }
(i.e. surround with {})
That said, value1 and value2 should be url encoded. If they are a simple string (e..g a_b) then this would be find as is but if it is for exmaple https://a.b it should be converted to https%3A%2F%2Fa.b
The easiest way I found to do this is to use https://www.urlencoder.org/ to convert it. convert each param separately and put the converted value instead of the original one.
Here is the screenshot from the solution that works for me, I hope it will be helpful. This is example with Microsoft Graph API but will work with any other scenario:
I use Content Security Policy. I get genuinely useful warnings like this:
CSP violation!
{ 'csp-report':
{ 'document-uri': 'about:blank',
referrer: '',
'violated-directive': 'img-src \'self\' data: pbs.twimg.com syndication.twitter.com p.typekit.net',
'original-policy': 'longPolicyGoesHere',
'blocked-uri': 'https://platform.twitter.com',
'source-file': 'https://platform.twitter.com',
'line-number': 2 } }
Cool, I need to add 'platform.twitter.com' as an img-src
But sometimes I get blank CSP warnings like this:
CSP violation!
{}
Ie, there's been a POST, but the JSON is empty. What do I do?
I found the problem in my case; it might not be the problem for you.
Since the CSP reporter calls the report-uri file with the POST method, I assumed that the $_POST variable would contain the posted data. This turned out to be false, because the data was not sent from a form or file upload (see PHP "php://input" vs $_POST).
The following code works for me perfectly (thanks to inspiration by the slightly buggy code in https://mathiasbynens.be/notes/csp-reports):
<?php
// Receive and log Content-Security-Policy report
// (WriteLog function omitted here: it just writes text into a log file)
$data=file_get_contents('php://input');
if (!$data) // Data is usually non-empty
exit(0);
// Prettify the JSON-formatted data.
$val=json_decode($data);
$data = json_encode($val,JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
WriteLog($data);
?>
I'm implementing an ActiveSync Java client. I can already communicate with the server and perform the protocol sequence to Sync emails, as defined in the documentation.
However, when I try and send a Sync command it seems I can only use a subset of the available commands in the specification. When I use certain property tags in the Sync XML message I receive a Status 4 ('Protocol Error') code, even though these should be valid according to the specification.
When I use only the GetChanges property I do get a proper response, however I'd like to be able to specify how many items to return etc.
I've included the XML snippet that I'm sending: the commented out lines are lines that were attempted but caused a Status 4.
<?xml version="1.0" ?>
<Sync xmlns="AirSync:">
<Collections>
<Collection>
<Class>Email</Class>
<SyncKey>{23423972324}</SyncKey>
<CollectionId>{23423sdfsdfsdfsf972324}</CollectionId>
<GetChanges/>
<!--<GetChanges>0</GetChanges>-->
<!--<WindowSize>512</WindowSize>-->
<!--<Options>-->
<!--<Class>Email</Class>-->
<!--<FilterType>3</FilterType>-->
<!--<MaxItems>10</MaxItems>-->
<!--</Options>-->
<!--<Commands>-->
<!-- <Fetch>-->
<!-- <ServerId>1:323</ServerId>-->
<!-- </Fetch>-->
<!--</Commands>-->
</Collection>
</Collections>
<!--<WindowSize>512</WindowSize>-->
</Sync>
Is there any reason why these properties shouldn't be supported? Or is there something I've left out of the message?
The GetOptions command for the server returns the following (truncated):
Server: Microsoft-IIS/6.0,
X-Powered-By: ASP.NET,
Pragma: no-cache,
Public: OPTIONS, POST, Allow: OPTIONS, POST,
MS-Server-ActiveSync: 6.5.7653.19,
MS-ASProtocolVersions: 1.0,2.0,2.1,2.5,
MS-ASProtocolCommands:Sync,SendMail,SmartForward,SmartReply,GetAttachment,GetHierarchy,CreateCollection,DeleteCollection,MoveCollection,FolderSync,FolderCreate,FolderDelete,FolderUpdate,MoveItems,GetItemEstimate,MeetingResponse,ResolveRecipients,ValidateCert,Provision,Search,Notify,Ping
It turns out that the WBXML encode/decoder I was using wasn't working correctly. I figured this out by comparing the byte code generated by two different WBXML encoders and saw a difference. The encoder I was using didn't process empty elements like properly. I fixed it and now the server acts as expected.