private async Task ApplyContentSecurityPolicy(TagHelperOutput output, string uniqueId) { ContentSecurityPolicyHelper cspHelper = new ContentSecurityPolicyHelper(ViewContext); ContentSecurityPolicyInlineExecution currentInlineExecution = cspHelper.GetCurrentInlineExecution(output.TagName); if (currentInlineExecution == ContentSecurityPolicyInlineExecution.Nonce) { output.Attributes.Add(ContentSecurityPolicyHelper.NonceAttribute, cspHelper.GetCurrentNonce()); } else if (currentInlineExecution.IsHashBased()) { string contentHash = null; if (!String.IsNullOrEmpty(uniqueId)) { contentHash = cspHelper.GetHashFromCache(uniqueId); } if (contentHash == null) { string content = output.Content.IsModified ? output.Content.GetContent() : (await output.GetChildContentAsync()).GetContent(); contentHash = ContentSecurityPolicyHelper.ComputeHash(currentInlineExecution, content); if (!String.IsNullOrEmpty(uniqueId)) { cspHelper.AddHashToCache(uniqueId, contentHash); } } cspHelper.AddHashToInlineExecutionSources(output.TagName, contentHash); } }
public void Dispose() { if (_currentInlineExecution.IsHashBased()) { StringBuilder elementInnerHtmlBuilder = ((StringWriter)_viewContext.Writer).GetStringBuilder(); string elementInnerHtml = elementInnerHtmlBuilder.ToString(); string elementHash = ContentSecurityPolicyHelper.ComputeHash(_currentInlineExecution, elementInnerHtml); _cspHelper.AddHashToInlineExecutionSources(_elementTag.TagName, elementHash); _viewContext.Writer.Dispose(); _viewContext.Writer = _viewContextWriter; _viewContext.Writer.Write(elementInnerHtml); } _elementTag.TagRenderMode = TagRenderMode.EndTag; _elementTag.WriteTo(_viewContext.Writer, HtmlEncoder.Default); }