---
title: "Flash安全域学习笔记"
author: "cuixuxucui"
date: "2011-07-19T11:10:50Z"
tags: []
categories: ["Web前端"]
slug: "flash"
draft: false
lastmod: "2011-07-19T11:10:50Z"
id: 1127721
url: "https://smartblack.iteye.com/blog/1127721"
---

Flash安全域学习笔记

参考：

[深入理解Flash Player的安全域（Security Domains）](http://riaoo.com/?p=1955)

 

1.什么叫相同域，什么叫不同的域呢？当两个域具有相同的协议(如http), 相同的端口(如80)，相同的host（如www.example.org)，那么我们就可以认为它们是相同的域。比如 http://www.example.org/index.html和http://www.example.org/sub/index.html是同域，而http://www.example.org, https://www.example.org, http://www.example.org:8080, http://sub.example.org中的任何两个都将构成跨域。

摘自http://www.woiweb.net/10-cross-domain-methods.html

2.如何在本地测试跨域访问？

编辑 hosts 文件，虚拟出多个域名出来。如：

127.0.0.1 www.1.com

127.0.0.1 www.2.com

新建一个AS工程，生成两个swf，比如A.swf和B.swf。然后在A中加载B即可，代码如下：

var loader:Loader = new Loader();

loader.contentLoaderInfo.addEventListener(Event.INIT, init);

var url:String = "http://www.1.com/B.swf";

loader.load(new URLRequest(url)); 

function init(event:Event):void {

trace(loader.content);

}

由于B属于www.1.com域，当我们打开www.2.com/A.swf或localhost/A.swf时就会报出安全错误。

SecurityError: Error #2121: 安全沙箱冲突:Loader.content:http://www.2.com/A.swf 不能访问 http://www.1.com/B.swf。可以通过调用 Security.allowDomain 来避免此冲突。

at flash.display::Loader/get content()

at Function/DomainTest/private:domainTest/init()\[E:\\cuixuWorkSpace\\SecurityTest\\src\\A.as:23]

解决办法就是在B.swf中添加：

Security.allowDomain("www.2.com");

3.由于不可执行文件（也就是非SWF文件）不能调用allowDomain代码，所以这类文件的信任机制在Flash Player中有不一样的处理方法。这就是跨域（cross-domain）策略文件派上用场的地方。跨域策略文件是一个放在网站的根域名下的命名为crossdomain.xml的XML文件。和allowDomain类似，定义了一组可以被Flash Player加载的安全网站域名。一个简单的跨域策略文件的例子如下：

http://example.com/crossdomain.xml:

&lt;?xml version="1.0"?&gt;

&lt;cross-domain-policy&gt;

&lt;site-control permitted-cross-domain-policies="by-content-type"/&gt;

&lt;allow-access-from domain="\*.example.com"/&gt;

&lt;allow-access-from domain="www.example-partner.com"/&gt;

&lt;/cross-domain-policy&gt;

这表示允许来自example.com的任意子域或www.example-partner.com的SWF文件加载example.com下的文件。

4.本地安全域

在硬盘上运行的SWF文件同样有自己的安全域。本地安全域有自己独特的行为，共分为4种安全沙箱类型：local-with-file, local-with-network, local-trusted, and application for AIR（本文不详细讨论AIR）。再加上网络上的SWF，一共有5种安全沙箱。

对于本地的信任文件，相同的问题是我们没有地方来保存跨域策略文件。把SWF或者包含SWF的文件夹添加到信任位置的话只需要添加路径到Flash Player的#Security\\FlashPlayerTrust下的.cfg文件就可以了。(C:\\Documents and Settings\\\[username]\\Application Data\\Macromedia\\Flash Player\\#Security\\FlashPlayerTrust)

这些文件就像你本地的跨域策略文件一样。当Flash Player读取的时候，信任授权给SWF，并覆盖SWF文件中关于本地访问权限的标识，从而允许受信的SWF能够同时访问本地和网络。