1- using System ;
1+ using System ;
22using System . Security . Cryptography ;
33using Newtonsoft . Json ;
44using 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