A enhanced secure Blazor iFrame component with built-in origin validation, bidirectional messaging, navigation tracking, and comprehensive security features.
$ dotnet add package BlazorFrameA Blazor component that provides an enhanced iframe wrapper with automatic resizing, cross-frame communication, and seamless JavaScript interop with built-in security features.
Install the package via NuGet Package Manager:
dotnet add package BlazorFrame
Or via Package Manager Console:
Install-Package BlazorFrame
@using BlazorFrame
<BlazorFrame Src="https://example.com" />
The component automatically derives allowed origins from the Src URL for secure messaging.
@using BlazorFrame
@using BlazorFrame.Models
<BlazorFrame Src="@iframeUrl"
Width="100%"
Height="400px"
EnableAutoResize="true"
EnableScroll="false"
OnLoad="HandleIframeLoad"
OnValidatedMessage="HandleValidatedMessage"
OnSecurityViolation="HandleSecurityViolation"
class="my-custom-iframe" />
@code {
private string iframeUrl = "https://example.com";
private Task HandleIframeLoad()
{
Console.WriteLine("Iframe loaded successfully!");
return Task.CompletedTask;
}
private Task HandleValidatedMessage(IframeMessage message)
{
Console.WriteLine($"Secure message from {message.Origin}: {message.Data}");
return Task.CompletedTask;
}
private Task HandleSecurityViolation(IframeMessage violation)
{
Console.WriteLine($"Security violation: {violation.ValidationError}");
return Task.CompletedTask;
}
}
@using BlazorFrame
@using BlazorFrame.Models
<BlazorFrame Src="@iframeUrl"
AllowedOrigins="@allowedOrigins"
SecurityOptions="@securityOptions"
OnValidatedMessage="HandleValidatedMessage"
OnSecurityViolation="HandleSecurityViolation" />
@code {
private string iframeUrl = "https://widget.example.com";
private List<string> allowedOrigins = new()
{
"https://widget.example.com",
"https://api.example.com"
};
private MessageSecurityOptions securityOptions = new()
{
EnableStrictValidation = true,
MaxMessageSize = 32 * 1024, // 32KB
LogSecurityViolations = true
};
private Task HandleValidatedMessage(IframeMessage message)
{
// Handle validated, secure messages
return Task.CompletedTask;
}
private Task HandleSecurityViolation(IframeMessage violation)
{
// Log, alert, or take corrective action
Logger.LogWarning("Security violation: {Error}", violation.ValidationError);
return Task.CompletedTask;
}
}| Parameter | Type | Default | Description |
|---|---|---|---|
Src | string | "" | The URL to load in the iframe |
Width | string | "100%" | The width of the iframe |
Height | string | "600px" | The initial height of the iframe |
EnableAutoResize | bool | true | Whether to automatically resize the iframe based on content height |
EnableScroll | bool | false | Whether to enable scrolling within the iframe wrapper |
AllowedOrigins | List<string>? | null | Explicit list of allowed origins. If null, auto-derives from Src |
SecurityOptions | MessageSecurityOptions | new() | Security configuration options |
OnLoad | EventCallback | - | Callback fired when the iframe loads |
OnMessage | EventCallback<string> | - | Callback fired when receiving valid postMessage (legacy) |
OnValidatedMessage | EventCallback<IframeMessage> | - | Callback fired with full message validation details |
OnSecurityViolation | EventCallback<IframeMessage> | - | Callback fired when security violations occur |
AdditionalAttributes | Dictionary<string, object> | - | Additional HTML attributes to apply |
BlazorFrame automatically validates message origins to prevent unauthorized communication:
All incoming messages are validated before reaching your application:
public class MessageSecurityOptions
{
/// <summary>List of allowed origins (null = auto-derive from Src)</summary>
public List<string>? AllowedOrigins { get; set; }
/// <summary>Enable strict JSON format validation</summary>
public bool EnableStrictValidation { get; set; } = true;
/// <summary>Maximum message size (default: 64KB)</summary>
public int MaxMessageSize { get; set; } = 64 * 1024;
/// <summary>Log security violations</summary>
public bool LogSecurityViolations { get; set; } = true;
}public class IframeMessage
{
public required string Origin { get; init; } // Verified sender origin
public required string Data { get; init; } // Validated JSON string
public bool IsValid { get; init; } // Security validation result
public string? ValidationError { get; init; } // Error details (if any)
public string? MessageType { get; init; } // Extracted message type
}Monitor and respond to security events:
<BlazorFrame OnSecurityViolation="HandleViolation" />
@code {
private Task HandleViolation(IframeMessage violation)
{
// Log, alert, or take corrective action
Logger.LogWarning("Security violation: {Error}", violation.ValidationError);
return Task.CompletedTask;
}
}BlazorFrame can automatically adjust the iframe height based on the content inside when EnableAutoResize is set to true (default). The component:
EnableAutoResize="false"// Inside your iframe content - specify target origin for security
window.parent.postMessage({
type: 'custom',
data: 'Hello from iframe!'
}, 'https://your-parent-domain.com');// Send resize messages (validated automatically)
window.parent.postMessage({
type: 'resize',
height: 800
}, 'https://your-parent-domain.com');private Task HandleValidatedMessage(IframeMessage message)
{
// message.Origin - verified sender origin
// message.Data - validated JSON string
// message.MessageType - extracted message type (if present)
// message.IsValid - always true in this callback
return Task.CompletedTask;
}The component includes built-in CSS styling with wrapper classes:
EnableScroll="true"The wrapper provides:
<!-- Web pages -->
<BlazorFrame Src="https://docs.microsoft.com" />
<!-- Local HTML files -->
<BlazorFrame Src="./local-content.html" />
<!-- Data URLs -->
<BlazorFrame Src="data:text/html,<h1>Hello World!</h1>" /><BlazorFrame Src="https://widget.example.com"
AllowedOrigins="@(new List<string>
{
"https://widget.example.com",
"https://api.example.com"
})" /><BlazorFrame Src="@secureUrl"
SecurityOptions="@(new MessageSecurityOptions
{
EnableStrictValidation = true,
MaxMessageSize = 16 * 1024, // 16KB limit
LogSecurityViolations = true
})"
OnSecurityViolation="HandleViolation" /><div class="container-fluid">
<BlazorFrame Src="@contentUrl"
Width="100%"
Height="calc(100vh - 200px)"
EnableAutoResize="false"
style="min-height: 400px;" />
</div><BlazorFrame Src="@contentUrl"
Width="100%"
Height="500px"
EnableAutoResize="false"
EnableScroll="true" /><BlazorFrame Src="@iframeUrl"
Width="800px"
Height="600px"
EnableAutoResize="false"
EnableScroll="true"
class="border rounded shadow"
style="margin: 20px;"
sandbox="allow-scripts allow-same-origin" />BlazorFrame works in all modern browsers that support:
This project is licensed under the MIT License - see the LICENSE file for details.
If you encounter any issues or have questions: