完全隔离的css 和 js , 但又可以使用 contentWindow和parent 来通信. 松耦合又不失灵活
通常为了防止被恶意嵌套,网站都会设置允许信任站点进行资源嵌套
Core允许我们自定义中间件来实现我们想要的功能,例如权限校验,跨域访问,服务注册等等
/// <summary> /// 响应头的增删方法 /// </summary> public class SecurityHeadersBuilder { private readonly SecurityHeadersPolicy _policy = new SecurityHeadersPolicy(); public SecurityHeadersBuilder AddCustomHeader(string header, string value) { _policy.SetHeaders[header] = value; return this; } public SecurityHeadersBuilder RemoveHeader(string header) { _policy.RemoveHeaders.Add(header); return this; } public SecurityHeadersPolicy Build() { return _policy; } }
/// <summary> /// 中间件拓展方法(在响应头添加、修改内容) /// </summary> public static class UseSecurityHeaders { public static IApplicationBuilder UseSecurityHeadersMiddleware(this IApplicationBuilder app, SecurityHeadersBuilder builder) { SecurityHeadersPolicy policy = builder.Build(); return app.UseMiddleware<SecurityHeadersMiddleware>(policy); } } /// <summary> /// 中间件实现 /// </summary> public class SecurityHeadersMiddleware { private readonly RequestDelegate _next; private readonly SecurityHeadersPolicy _policy; public SecurityHeadersMiddleware(RequestDelegate next, SecurityHeadersPolicy policy) { _next = next; _policy = policy; } public async Task Invoke(HttpContext context) { IHeaderDictionary headers = context.Response.Headers; foreach (var headerValuePair in _policy.SetHeaders) { headers[headerValuePair.Key] = headerValuePair.Value; } foreach (var header in _policy.RemoveHeaders) { headers.Remove(header); } await _next(context); } } /// <summary> /// 响应头的增删集合 /// </summary> public class SecurityHeadersPolicy { public IDictionary<string, string> SetHeaders { get; } = new Dictionary<string, string>(); public ISet<string> RemoveHeaders { get; } = new HashSet<string>(); }
在startup.cs的Configure方法中使用中间件进行响应头信息修改
//允许iframe嵌入资源 app.UseSecurityHeadersMiddleware(new SecurityHeadersBuilder() .AddCustomHeader("X-Frame-Options", "AllowAll") .AddCustomHeader("Access-Control-Allow-Credentials", "true") .AddCustomHeader("Access-Control-Allow-Origin","http://localhost:8081,http://localhost:8082") );