Skip to content

Commit 19854c5

Browse files
danatcofoTodd LairDaniel Gidman
authored
(DOTNET-123) Allow nonce attribute value to be passed in (#134)
* DOTNET-116 add nonce attribute to script tag for CSP support * DOTNET-116 provide the ability to set a nonce value for the script Co-authored-by: Todd Lair <[email protected]> Co-authored-by: Daniel Gidman <[email protected]>
1 parent 307064e commit 19854c5

File tree

1 file changed

+15
-8
lines changed

1 file changed

+15
-8
lines changed

Src/StackifyLib/Web/RealUserMonitoring.cs

Lines changed: 15 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
using System;
1+
using System;
22
using System.Security.Cryptography;
33
using Newtonsoft.Json;
44
using Newtonsoft.Json.Linq;
@@ -9,8 +9,12 @@ namespace StackifyLib.Web
99
public static class RealUserMonitoring
1010
{
1111
private static readonly RandomNumberGenerator Rng = new RNGCryptoServiceProvider();
12-
13-
public static string GetHeaderScript()
12+
13+
/// <summary>
14+
/// Generate the header script for including RUM
15+
/// </summary>
16+
/// <param name="nonce">nonce value, defaults to a cryptographic unique string if left null</param>
17+
public static string GetHeaderScript(string nonce = null)
1418
{
1519
var rumScriptUrl = Config.RumScriptUrl;
1620
var rumKey = Config.RumKey;
@@ -52,13 +56,16 @@ public static string GetHeaderScript()
5256
settings["Trans"] = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(reportingUrl));
5357
}
5458

55-
// generate nonce for strict CSP rules
59+
return string.Format("<script type=\"text/javascript\" nonce=\"{3}\">(window.StackifySettings || (window.StackifySettings = {0}))</script><script src=\"{1}\" data-key=\"{2}\" async></script>",
60+
settings.ToString(Formatting.None), rumScriptUrl, rumKey, nonce ?? GetNonce());
61+
}
62+
63+
// generate nonce for strict CSP rules
64+
private static string GetNonce()
65+
{
5666
var nonceBytes = new byte[20];
5767
Rng.GetNonZeroBytes(nonceBytes);
58-
var nonce = Convert.ToBase64String(nonceBytes);
59-
60-
return string.Format("<script type=\"text/javascript\" nonce=\"{3}\">(window.StackifySettings || (window.StackifySettings = {0}))</script><script src=\"{1}\" data-key=\"{2}\" async></script>",
61-
settings.ToString(Formatting.None), rumScriptUrl, rumKey, nonce);
68+
return Convert.ToBase64String(nonceBytes);
6269
}
6370
}
6471
}

0 commit comments

Comments
 (0)