Spring MVC lets you handle CORS (Cross-Origin Resource Sharing). This section describes how to do so.
Spring MVC 允许您处理 CORS(跨源资源共享)。本节将描述如何进行操作。
For security reasons, browsers prohibit AJAX calls to resources outside the current origin. For example, you could have
your bank account in one tab and evil.com in another.
出于安全原因,浏览器禁止对当前源以外的资源进行 AJAX 调用。例如,您可以在一个标签页中拥有您的银行账户,在另一个标签页中打开
evil.com。
Scripts from evil.com should not be able to make AJAX requests to your bank API with your credentials — for example
withdrawing money from your account!
脚本从 evil.com 不应能够使用您的凭证向您的银行 API 发起 AJAX 请求——例如从您的账户中取款!
Cross-Origin Resource Sharing (CORS) is a W3C specification implemented
by most browsers that lets you specify what kind of cross-domain requests are
authorized, rather than using less secure and less powerful workarounds based on IFRAME or JSONP.
跨源资源共享(CORS)是一种由大多数浏览器实现的 W3C 规范,允许您指定哪些跨域请求被授权,而不是使用基于 IFRAME 或 JSONP
的较不安全和功能较弱的替代方案。
The CORS specification distinguishes between preflight, simple, and actual requests. To learn how CORS works, you can
read this article, among many others, or see the specification
for more details.
CORS 规范区分了预检、简单和实际请求。要了解 CORS 的工作原理,您可以阅读这篇文章,以及其他许多文章,或查看规范以获取更多详细信息。
Spring MVC HandlerMapping implementations provide built-in support for CORS. After successfully mapping a request to a
handler, HandlerMapping implementations check the CORS configuration for the given request and handler and take
further actions. Preflight requests are handled directly, while simple and actual CORS requests are intercepted,
validated, and have required CORS response headers set.
Spring MVC HandlerMapping 实现提供了对 CORS 的内置支持。在成功映射请求到处理器之后, HandlerMapping 实现会检查给定请求和处理器对应的
CORS 配置,并采取进一步行动。预检请求直接处理,而简单和实际的 CORS 请求则被拦截、验证,并设置所需的 CORS 响应头。
In order to enable cross-origin requests (that is, the Origin header is present and differs from the host of the
request), you need to have some explicitly declared CORS configuration. If no matching CORS configuration is found,
preflight requests are rejected.
为了启用跨源请求(即,存在且与请求主机不同的 Origin 头),您需要有一些明确声明的 CORS 配置。如果没有找到匹配的 CORS
配置,则预检请求将被拒绝。
No CORS headers are added to the responses of simple and actual CORS requests and, consequently, browsers reject them.
没有添加 CORS 头到简单和实际的 CORS 请求的响应中,因此浏览器拒绝它们。
Each HandlerMapping can
be configured
individually with URL pattern-based CorsConfiguration mappings. In most cases, applications use the MVC Java
configuration or the XML namespace to declare such mappings, which results in a single global map being passed to all
HandlerMapping instances.
每个 HandlerMapping 都可以通过基于 URL 模式的 CorsConfiguration 映射进行单独配置。在大多数情况下,应用程序使用 MVC
Java 配置或 XML 命名空间来声明此类映射,这导致一个全局映射被传递给所有 HandlerMapping 实例。
You can combine global CORS configuration at the HandlerMapping level with more fine-grained, handler-level CORS
configuration. For example, annotated controllers can use class- or method-level @CrossOrigin annotations (other
handlers can implement CorsConfigurationSource).
您可以将在 HandlerMapping 级别的全局 CORS 配置与更细粒度的、处理程序级别的 CORS 配置相结合。例如,注解控制器可以使用类或方法级别的
@CrossOrigin 注解(其他处理程序可以实现 CorsConfigurationSource )。
The rules for combining global and local configuration are generally additive — for example, all global and all local
origins. For those attributes where only a single value can be accepted, e.g. allowCredentials and maxAge, the local
overrides the global value. See
CorsConfiguration#combine(CorsConfiguration)
for more details.
全局和本地配置的组合规则通常是累加的——例如,所有全局和所有本地来源。对于只能接受单个值的属性,例如 allowCredentials 和
maxAge ,本地值覆盖全局值。有关更多详细信息,请参阅 CorsConfiguration#combine(CorsConfiguration) 。
To learn more from the source or make advanced customizations, check the code behind:
为了从源代码中获取更多信息或进行高级自定义,请查看背后的代码:
CorsConfiguration
CorsProcessor, DefaultCorsProcessor
AbstractHandlerMapping
1.7.3. 认证请求
Using CORS with credentialed requests requires enabling allowedCredentials. Be aware that this option establishes a
high level of trust with the configured domains and also increases the surface of attack of the web application by
exposing sensitive user-specific information such as cookies and CSRF tokens.
使用带有凭据的请求与 CORS 一起使用需要启用 allowedCredentials 。请注意,此选项与配置的域建立了高度信任,同时也通过暴露敏感的用户特定信息(如
cookies 和 CSRF 令牌)增加了 Web 应用程序的攻击面。
Enabling credentials also impacts how the configured "*" CORS wildcards are processed:
启用凭据也会影响配置的 "*" CORS 通配符的处理方式:
Wildcards are not authorized in allowOrigins, but alternatively the allowOriginPatterns property may be used to
match to a dynamic set of origins.
通配符在 allowOrigins 中未授权,但可以使用 allowOriginPatterns 属性来匹配动态的源集合。
When set on allowedHeaders or allowedMethods, the Access-Control-Allow-Headers and
Access-Control-Allow-Methods response headers are handled by copying the related headers and method specified in the
CORS preflight request.
当设置为 allowedHeaders 或 allowedMethods 时, Access-Control-Allow-Headers 和 Access-Control-Allow-Methods
响应头通过复制 CORS 预请求中指定的相关头和方法来处理。
When set on exposedHeaders, Access-Control-Expose-Headers response header is set either to the configured list of
headers or to the wildcard character. While the CORS spec does not allow the wildcard character when
Access-Control-Allow-Credentials is set to true, most browsers support it and the response headers are not all
available during the CORS processing, so as a consequence the wildcard character is the header value used when
specified regardless of the value of the allowCredentials property.
当设置为 exposedHeaders 时, Access-Control-Expose-Headers 响应头设置为配置的头列表或通配符字符。虽然 CORS 规范不允许当
Access-Control-Allow-Credentials 设置为 true 时使用通配符字符,但大多数浏览器支持它,并且在 CORS
处理期间并非所有响应头都可用,因此,作为结果,通配符字符是当指定时使用的头值,无论 allowCredentials 属性的值如何。
While such wildcard configuration can be handy, it is recommended when possible to configure a finite set of values
instead to provide a higher level of security.
虽然这种通配符配置可能很方便,但建议在可能的情况下,配置一个有限值的集合,以提供更高的安全性。
@CrossOriginThe
@CrossOrigin
annotation enables cross-origin requests on annotated controller methods, as the following example shows:
@CrossOrigin 注解允许在注解的控制器方法上启用跨域请求,如下例所示:
By default, @CrossOrigin allows:默认情况下, @CrossOrigin 允许:
All origins. 所有来源。
All headers. 所有头部。
All HTTP methods to which the controller method is mapped.
所有映射到控制器方法的 HTTP 方法。
allowCredentials is not enabled by default, since that establishes a trust level that exposes sensitive user-specific
information (such as cookies and CSRF tokens) and should only be used where appropriate. When it is enabled either
allowOrigins must be set to one or more specific domain (but not the special value "*") or alternatively the
allowOriginPatterns property may be used to match to a dynamic set of origins.
allowCredentials 默认未启用,因为这会建立一个信任级别,暴露敏感的用户特定信息(如 cookies 和 CSRF
令牌),并且仅在适当的情况下使用。当启用时,要么 allowOrigins 必须设置为一个或多个特定域名(但不能是特殊值 "*" ),或者可以使用
allowOriginPatterns 属性来匹配一组动态源。
maxAge is set to 30 minutes.
maxAge 设置为 30 分钟。
@CrossOrigin is supported at the class level, too, and is inherited by all methods, as the following example shows:
@CrossOrigin 也在类级别上得到支持,并且由所有方法继承,如下例所示:
You can use @CrossOrigin at both the class level and the method level, as the following example shows:
您可以在类级别和方法级别上使用 @CrossOrigin ,如下例所示:
1.7.5. 全局配置
In addition to fine-grained, controller method level configuration, you probably want to define some global CORS
configuration, too. You can set URL-based CorsConfiguration mappings individually on any HandlerMapping. Most
applications, however, use the MVC Java configuration or the MVC XML namespace to do that.
除了细粒度、控制器方法级别的配置之外,你可能还想定义一些全局的 CORS 配置。你可以在任何地方单独设置基于 URL 的
CorsConfiguration 映射。然而,大多数应用程序使用 MVC Java 配置或 MVC XML 命名空间来完成这项工作。
By default, global configuration enables the following:
默认情况下,全局配置启用了以下功能:
All origins. 所有来源。
All headers. 所有头部。
GET, HEAD, and POST methods.
GET 、 HEAD 和 POST 方法。
allowCredentials is not enabled by default, since that establishes a trust level that exposes sensitive user-specific
information (such as cookies and CSRF tokens) and should only be used where appropriate. When it is enabled either
allowOrigins must be set to one or more specific domain (but not the special value "*") or alternatively the
allowOriginPatterns property may be used to match to a dynamic set of origins.
allowCredentials 默认未启用,因为这会建立一个信任级别,暴露敏感的用户特定信息(如 cookies 和 CSRF
令牌),并且仅在适当的情况下使用。当启用时,要么 allowOrigins 必须设置为一个或多个特定域名(但不能是特殊值 "*" ),或者可以使用
allowOriginPatterns 属性来匹配一组动态源。
maxAge is set to 30 minutes.
maxAge 设置为 30 分钟。
To enable CORS in the MVC Java config, you can use the CorsRegistry callback, as the following example shows:
要启用 MVC Java 配置中的 CORS,您可以使用 CorsRegistry 回调,如下例所示:
To enable CORS in the XML namespace, you can use the <mvc:cors> element, as the following example shows:
要启用 XML 命名空间中的 CORS,您可以使用 <mvc:cors> 元素,如下例所示:
You can apply CORS support through the built-in
CorsFilter.
您可以通过内置的 CorsFilter 应用 CORS 支持。
If you try to use the CorsFilter with Spring Security, keep in mind that Spring Security
has built-in support for CORS.
如果您尝试使用 CorsFilter 与 Spring Security 一起使用,请注意 Spring Security 内置了对 CORS 的支持。
To configure the filter, pass a CorsConfigurationSource to its constructor, as the following example shows:
为了配置过滤器,将其构造函数传递一个 CorsConfigurationSource ,如下例所示: