I'm trying to make a simple REST API call but it seems security policies are stopping me and I don't know how to fix it. The code makes a call to an open API to get a joke. However I get the following error:
dotnet.6.0.11.pbddgabtj1.js:1 Refused to connect to 'http://api.chucknorris.io/jokes/random' because it violates the document's Content Security Policy.
I have added the content security policy to my header in wwwroot/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
<base href="/" />
<link href="css/bootstrap/bootstrap.min.css" rel="stylesheet" />
<link href="css/app.css" rel="stylesheet" />
<meta http-equiv="Content-Security-Policy"
content="base-uri 'self';
block-all-mixed-content;
default-src 'self';
img-src data: https:;
object-src 'none';
script-src 'self'
'sha256-v8v3RKRPmN4odZ1CWM5gw80QKPCCWMcpNeOmimNL2AA='
'unsafe-eval';
style-src 'self'
'unsafe-inline';
upgrade-insecure-requests;">
</head>
<body>
<div id="app">Loading...</div>
<div id="blazor-error-ui">
An unhandled error has occurred.
Reload
<a class="dismiss">🗙</a>
</div>
<script src="_framework/blazor.webassembly.js"></script>
</body>
</html>
The component that does the call looks like this:
#page "/"
<PageTitle>Index</PageTitle>
<br />
<h4>Joke of the day:</h4>
<p>#joke</p>
#code{
string joke = "No Joke";
private readonly HttpClient clientHttp;
public Index()
{
clientHttp = new HttpClient();
}
protected override async Task OnInitializedAsync(){
var url = new Uri("http://api.chucknorris.io/jokes/random");
joke = "";
try
{
var result = await clientHttp.GetAsync(url);
joke = result.ToString();
}
catch (Exception e)
{
Console.WriteLine("Failed to get the joke. Error: ", e.Message);
}
if (string.IsNullOrEmpty(joke))
joke = "No Joke";
}
}
Any ideas what I'm missing?
Found the answer. You need to whitelist the API call.
<meta http-equiv="Content-Security-Policy"
content="base-uri 'self';
block-all-mixed-content;
default-src 'self';
font-src 'self';
connect-src 'self'
https://api.chucknorris.io/jokes/random;
img-src data: https:;
object-src 'none';
script-src 'self'
'sha256-v8v3RKRPmN4odZ1CWM5gw80QKPCCWMcpNeOmimNL2AA='
'unsafe-eval';
style-src 'self'
'unsafe-inline';
upgrade-insecure-requests;">
Related
Does script-src parameter using hashes works for inline scripts only?
This config works for for me (inline script in HTML code):
Apache config:
Header set Content-Security-Policy-Report-Only: "script-src 'sha256-U82JgRvGjy4mzia+G8DutvX8V/W33LIoO2UuwT+rE/0='"
HTML code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Hello!</title>
</head>
<body>
<h1>Hello World!</h1>
<p>This is a simple paragraph.</p>
</body>
<script>alert('hello everybody')</script>
</html>
where:
U82JgRvGjy4mzia+G8DutvX8V/W33LIoO2UuwT+rE/0= is a sha256 hash code of
alert('hello everybody') converted into base64
Once I moved the same script alert('hello everybody') into separate js file test.js and have updated index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Hello!</title>
</head>
<body>
<h1>Hello World!</h1>
<p>This is a simple paragraph.</p>
</body>
<script src="test.js"></script>
</html>
CSP blocking test.js file, however hash for it still the same
[Report Only] Refused to load the script 'http://localhost/test.js'
because it violates the following Content Security Policy directive:
"script-src 'sha256-U82JgRvGjy4mzia+G8DutvX8V/W33LIoO2UuwT+rE/0='".
Note that 'script-src-elem' was not explicitly set, so 'script-src' is
used as a fallback.
What parameter should I use for CSP to allow local js file by hash?
This should allow loading a script from the same source: "script-src 'self';"
I'm working on a vscode extension that works with a webview and i'm new to vscode extension and web development.
I made a webview with svelte but everytime i switch to another tab and come back to my webview's tab everything reloads.
I generated the html of the webview by a function who alse load the compiled components made in svelte.
function getGenericHTML(_webview: vscode.Webview, _extensionUri: vscode.Uri , _compiledElementName:string) : string {
// Local path to css styles in media folder
const stylesResetUri = _webview.asWebviewUri(vscode.Uri.joinPath(_extensionUri,"media","reset.css"));
const stylesMainUri = _webview.asWebviewUri(vscode.Uri.joinPath(_extensionUri,"media","vscode.css"));
const stylesBootstrap = _webview.asWebviewUri(vscode.Uri.joinPath(_extensionUri,"media","bootstrap.min.css"));
const scriptBootstrap = _webview.asWebviewUri(vscode.Uri.joinPath(_extensionUri,"media","bootstrap.bundle.min.js"));
// Svelte compiled elements
const scriptUri = _webview.asWebviewUri(vscode.Uri.joinPath(_extensionUri, "out", "compiled", _compiledElementName + ".js"));
const cssUri = _webview.asWebviewUri(vscode.Uri.joinPath(_extensionUri, "out", "compiled", _compiledElementName + ".css"));
// Use a nonce to only allow specific scripts to be run
const nonce = getNonce();
return `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="Content-Security-Policy" content="img-src https: data:; style-src 'unsafe-inline' ${ _webview.cspSource }; script-src 'nonce-${nonce}';">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="${stylesBootstrap}" rel="stylesheet" integrity=${"sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC"} crossorigin="anonymous">
<link href="${stylesResetUri}" rel="stylesheet">
<link href="${stylesMainUri}" rel="stylesheet">
<link href="${cssUri}" rel="stylesheet">
<script nonce="${nonce}">
tsvscode = acquireVsCodeApi();
</script>
</head>
<body>
</body>
<script nonce="${nonce}" src="${scriptUri}"></script>
<script nonce="${nonce}" src="${scriptBootstrap}" integrity=${"sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM"} crossorigin="anonymous"></script>
</html>`;
}
I need to declare the files to execute once? Did i miss something? Does anyone have some advice?
The full code of the extension is on github: https://github.com/ArkoMO93/al-translations.git
Thanks in advance
This is by design. If the webview is not visible, VS Code destroys it to reclaim memory. The webview is then automatically recreated when it becomes visible again. See https://code.visualstudio.com/api/extension-guides/webview#persistence for details about how to preserve state between unloads and reloads
If this doesn't work for your use case, you can enable retainContextWhenHidden in the WebviewPanelOptions. Again though, only do this if you absolutely need to
I'm working on .net 5 blazor wasm project. I recently updated my Visual Studio 2019 to version 16.10.0. All of a sudden I started getting an error message in my browser (Google Chrome) console as shown below:
Refused to load the script
'https://localhost:44340/_framework/aspnetcore-browser-refresh.js'
because it violates the following Content Security Policy directive:
"script-src 'sha256-fa5rxHhZ799izGRP38+h4ud5QXNT0SFaFlh4eqDumBI='".
Note that 'script-src-elem' was not explicitly set, so 'script-src' is
used as a fallback.
I don't have _framework/aspnetcore-browser-refresh.js added in my index.html. Here is the scripts and styles declaration in my index.html
styles declared inside <head> in index.html:
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
<title>App</title>
<base href="/" />
<link href="css/site.css" rel="stylesheet" />
<link href="Web.styles.css" rel="stylesheet">
<link href="_content/BlazorDateRangePicker/daterangepicker.min.css" rel="stylesheet" />
<link href="manifest.json" rel="manifest" />
<link rel="apple-touch-icon" sizes="512x512" href="icon-512.png" />
</head>
scripts in index.html:
<script src="_content/Microsoft.AspNetCore.Components.WebAssembly.Authentication/AuthenticationService.js"></script>
<script src="_framework/blazor.webassembly.js"></script>
<script src="js/Chart.js"></script>
<script src="js/print.js"></script>
<script src="js/pdf.js"></script>
<script src="_content/BlazorDateRangePicker/clickAndPositionHandler.js"></script>
<script src="js/blazorInterop.js"></script>
<script>navigator.serviceWorker.register('service-worker.js');</script>
But when I launch the app via visual studio, from the browser I can see that _framework/aspnetcore-browser-refresh.js gets appended to scripts section in my index.html. Here is the screen print.
This is anything related to my configuration error? or I need to setup CSP in my index.html? Please assist.
Looks like /_framework/aspnetcore-browser-refresh.js script belongs to a new Hot Reload feature.
Something was broken due to upgrade because message: it violates the following Content Security Policy directive: "script-src 'sha256-fa5rxHhZ799izGRP38+h4ud5QXNT0SFaFlh4eqDumBI='" says thay you have CSP script-src 'sha256-fa5rxHhZ799izGRP38+h4ud5QXNT0SFaFlh4eqDumBI=', but at the same time you load a lot of scripts:
<script src="_content/Microsoft.AspNetCore.Components.WebAssembly.Authentication/AuthenticationService.js"></script>
<script src="_framework/blazor.webassembly.js"></script>
<script src="js/Chart.js"></script>
<script src="js/print.js"></script>
<script src="js/pdf.js"></script>
<script src="_content/BlazorDateRangePicker/clickAndPositionHandler.js"></script>
<script src="js/blazorInterop.js"></script>
<script>navigator.serviceWorker.register('service-worker.js');</script>
At least you need to have 'self' in the script-src directive. Also the sha256-fa5rxHhZ799izGRP38+h4ud5QXNT0SFaFlh4eqDumBI= hash value does not match the hash of your navigator.serviceWorker.register('service-worker.js'); inline script.
You should have a lot of CSP errors in the console.
I am trying to fetch and display a map from the arcgis server using Aptana IDE. It says l is undefined.
GET https://gistest2.xxx.xxx/arcgis/rest/info?f=json
200 OK 27ms TypeError: l is undefined
...x)<=p.dx)&&q._addFrameInfo(h,p);this.setExclusionAreas(this.exclusionAreas);this...
Here is the entire code except the URL I am trying to hit.
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<!--The viewport meta tag is used to improve the presentation and behavior of the samples
on iOS devices-->
<meta name="viewport" content="initial-scale=1, maximum-scale=1,user-scalable=no">
<title>BGSU Memorial Trees Location</title>
<link rel="stylesheet" href="http://js.arcgis.com/3.10/js/dojo/dijit/themes/claro/claro.css">
<link rel="stylesheet" href="http://js.arcgis.com/3.10/js/esri/css/esri.css">
<script src="http://js.arcgis.com/3.10/">
</script>
<script>
var map;
require(["esri/map", "esri/layers/ArcGISTiledMapServiceLayer", "dojo/domReady!"],
function (Map, ArcGISTiledMapServiceLayer ) {
map = new Map("map", {
center: [-76.756, 40.241],
zoom: 8
});
var customBasemap = new ArcGISTiledMapServiceLayer(
"https://XXX/");
map.addLayer(customBasemap);
});
</script>
</head>
<body class="claro">
<div align="center"><strong>BGSU Memorial Trees Listing </strong><hr>
<i><a target="_self" href="listingtrees.html">Listing</a> | <a target="_self" href="locationtrees.html">Locations </a></i>
</div>
<br>
<div id="map" >
</div>
</body>
</html>
Any help is highly appreciated.
Thanks in Advance!
In the constructor of ArcGISTiledMapServiceLayer you have to specify the URL of an ArcGIS tiled map service. Example of URL:
http://myserver/arcgis/rest/services/map_service_name/MapServer
The address you specified (arcgis/rest/info?f=json) is the address of the REST service of ArcGIS Server but doesn't point to a Map service.
I am working on an opera extension. The extension have a popup that will open a website in it.
I get the below error at "xhr.send()" in popup.html file and i can't able to remove it.
"[4/14/2013 12:51:19 PM] JavaScript -
widget://wuid-9ec76e79-06d9-2749-8b7e-b42743de3375/popup.html Inline
script thread Uncaught exception: ReferenceError: Security violation
Error thrown at line 30, column 16 in fetchGames() in
widget://wuid-9ec76e79-06d9-2749-8b7e-b42743de3375/popup.html:
xhr.send(); called from line 32, column 12 in widget://wuid-9ec76e79-06d9-2749-8b7e-b42743de3375/popup.html:
fetchGames(); "
My config file is as below:
<?xml version="1.0" encoding="utf-8"?>
<widget xmlns="http://www.w3.org/ns/widgets" id="http://www.example.org/helloworld">
<name>Hello Extensions!</name>
<description>A simple hello world example</description>
<author href="http://www.twitter.com/dstorey/" email="dstorey#opera.com">David Storey, Opera Software</author>
<icon src="icons/icon-64.png"/>
</widget>
My index.html file is:
<!DOCTYPE HTML>
<html lang="en">
<head>
<title>Hello World!</title>
<meta charset="UTF-8">
<script>
window.addEventListener( 'load', function(){
var theButton;
var ToolbarUIItemProperties = {
disabled: false,
title: 'Hello World',
icon: 'icons/icon-18.png',
popup: {
href: 'popup.html',
width: 500,
height: 500
}
}
theButton = opera.contexts.toolbar.createItem(ToolbarUIItemProperties);
opera.contexts.toolbar.addItem(theButton);
}, false );
</script>
</head>
<body>
</body>
</html>
My popup.html file is:
<!DOCTYPE HTML>
<html lang="en">
<head>
<title></title>
<link href="style.css" rel="stylesheet" type="text/css" />
<style type="text/css">
body {
background-color: #efefef;
}
</style>
<script>
function fetchGames() {
alert('hello');
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(data) {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
var data = (xhr.responseText);
document.getElementById('list_games').innerHTML = data;
//callback(data);
}
else {
alert('No Games Found');
window.close();
}
}
}
var url = 'http://www.anatomic.us/generate-xml';
xhr.open('GET', url, true);
xhr.send();
};
fetchGames();
function submitForm(obj)
{
var searchKey = document.getElementById('sp').value;
if(searchKey!=null && searchKey!='')
{
obj.setAttribute('action', 'http://www.3d-game.co/'+searchKey);
return true;
// chrome.tabs.create({url: 'http://www.3d-game.co/'+searchKey});
}
else
{
alert('Please Enter your search item');
return false;
}
}
</script>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</head>
<body>
<!-- <div class="header">
<img src="icon.png">
</div>
<br />-->
<div id=content>
<div style='padding-left:10px;'>
<form id=sf method=post action="http://www.3d-game.co/search/" onSubmit="return submitForm(this);" target="_blank">
</form>
</div>
<div id=cat_content>
<div id="list_games" class=list_games>
<img src="loader.gif" border="none" />
<div class="ajax-loader">
<img src="loader.gif" border="none" />
</div>
</div>
</div>
</body>
</html>
Plz help me in removing it.
Add following in the header of the file from where you are fetching the data:
Access-Control-Allow-Origin: *
in config.xml file add this line: to allow any domain httprequest before tab, this solve the problem, if problems persist, open in opera browser tab "opera:config" and select "Users Prefs" and check "Allow File XMLHttpRequest" and restart. if have problem i can send you my opera extension working fine...