好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

Spring 跨域配置请求详解

介绍

跨站 http 请求(cross-site http request)是指发起请求的资源所在域不同于该请求所指向资源所在的域的 http 请求。比如说,域名a(http://domaina.example)的某 web 应用程序中通过标签引入了域名b(http://domainb.foo)站点的某图片资源(http://domainb.foo/image.jpg),域名a的那 web 应用就会导致浏览器发起一个跨站 http 请求。在当今的 web 开发中,使用跨站 http 请求加载各类资源(包括css、图片、javascript 脚本以及其它类资源),已经成为了一种普遍且流行的方式。

出于安全考虑,浏览器会限制脚本中发起的跨站请求。比如,使用 xmlhttprequest 对象发起 http 请求就必须遵守同源策略( same-origin policy )。 具体而言,web 应用程序能且只能使用 xmlhttprequest 对象向其加载的源域名发起 http 请求,而不能向任何其它域名发起请求。为了能开发出更强大、更丰富、更安全的web应用程序,开发人员渴望着在不丢失安全的前提下,web 应用技术能越来越强大、越来越丰富。比如,可以使用 xmlhttprequest 发起跨站 http 请求。(这段描述跨域不准确,跨域并非浏览器限制了发起跨站请求,而是跨站请求可以正常发起,但是返回结果被浏览器拦截了。最好的例子是crsf跨站攻击原理,请求是发送到了后端服务器无论是否跨域!注意:有些浏览器不允许从https的域跨域访问http,比如chrome和firefox,这些浏览器在请求还未发出的时候就会拦截请求,这是一个特例。)

普通参数跨域

在response的头文件添加

?

1

2

3

4

httpservletresponse.setheader( "access-control-allow-origin" , "*" );

httpservletresponse.setheader( "access-control-allow-methods" , "post" );

httpservletresponse.setheader( "access-control-allow-headers" , "access-control" );

httpservletresponse.setheader( "allow" , "post" );

 

参数 值 描述
access-control-allow-origin * 授权的源控制
access-control-allow-credentials true / false 是否允许用户发送和处理cookie
access-control-allow-methods [,]* 允许请求的http method,多个用逗号分隔
access-control-allow-headers [,]* 控制哪些header能发送真正的请求,多个用逗号分隔
access-control-max-age 授权的时间,单位为秒。有效期内,不会重复发送预检请求

 

带headr请求跨域

这样客户端需要发起options请求, 可以说是一个【预请求】,用于探测后续真正需要发起的跨域 post 请求对于服务器来说是否是安全可接受的,因为跨域提交数据对于服务器来说可能存在很大的安全问题。

因为springmvc模式是关闭options请求的,所以需要开启

?

1

2

3

4

5

6

7

8

9

<servlet> 

  <servlet-name>application</servlet-name>

  <servlet- class >org.springframework.web.servlet.dispatcherservlet</servlet- class >

  <init-param>

   <param-name>dispatchoptionsrequest</param-name>

   <param-value> true </param-value>

  </init-param>

  <load-on-startup> 1 </load-on-startup>

</servlet>

开启cors

springmvc从4.2版本开始增加了对cors的支持。在springmvc 中增加cors支持非常简单,可以配置全局的规则,也可以使用@crossorigin注解进行细粒度的配置。

使用@crossorigin注解

先通过源码看看该注解支持的属性

在controller上使用@crossorigin注解

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

// 指定当前的accountcontroller中所有的方法可以处理所有域上的请求

@crossorigin (origins = { "http://domain1.com" , "http://domain2.com" }, maxage = 72000l)

@restcontroller

@requestmapping ( "/account" )

public class accountcontroller {

 

  @requestmapping ( "/{id}" )

  public account retrieve( @pathvariable long id) {

   // ...

  }

 

  @requestmapping (method = requestmethod.delete, path = "/{id}" )

  public void remove( @pathvariable long id) {

   // ...

  }

}

在方法上使用@crossorigin注解

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

@crossorigin (maxage = 3600l)

@restcontroller

@requestmapping ( "/account" )

public class accountcontroller {

 

  @crossorigin (origins = { "http://domain1.com" , "http://domain2.com" })

  @requestmapping ( "/{id}" )

  public account retrieve( @pathvariable long id) {

   // ...

  }

 

  @requestmapping (method = requestmethod.delete, path = "/{id}" )

  public void remove( @pathvariable long id) {

   // ...

  }

}

cors全局配置

除了细粒度基于注解的配置,可以定义全局cors的配置。这类似于使用过滤器,但可以在spring mvc中声明,并结合细粒度@crossorigin配置。默认情况下所有的域名和get、head和post方法都是允许的。

基于xml的配置

?

1

2

3

4

5

6

7

8

9

10

11

12

<mvc:cors>

  <mvc:mapping path= "/api/**"

   allowed-origins= "http://domain1.com, http://domain2.com"

   allowed-methods= "get, post, put, head, patch, delete, options, trace"

   allowed-headers= "header1, header2, header3"

   exposed-headers= "header1, header2"

   allow-credentials= "false"

   max-age= "72000" />

 

   <mvc:mapping path= "/resources/**"

   allowed-origins= "http://domain3.com" />

</mvc:cors>

基于代码的配置

这个方法同样适用于springboot。

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

@configuration

public class webconfig extends webmvcconfigureradapter {

 

  @override

  public void addcorsmappings(corsregistry registry) {

   registry.addmapping( "/api/**" )

    .allowedorigins( "http://domain1.com" )

    .allowedorigins( "http://domain2.com" )

    .allowedmethods( "get" , "post" , "put" , "head" , "patch" , "delete" , "options" , "trace" );

    .allowedheaders( "header1" , "header2" , "header3" )

    .exposedheaders( "header1" , "header2" )

    .allowcredentials( false )

    .maxage(72000l);

   

   registry.addmapping( "/resources/**" )

    .allowedorigins( "http://domain3.com" );

  }

}

基于过滤器的配置

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

import org.springframework.web.cors.corsconfiguration;

import org.springframework.web.cors.urlbasedcorsconfigurationsource;

 

@bean

public filterregistrationbean corsfilter() {

  urlbasedcorsconfigurationsource source = new urlbasedcorsconfigurationsource();

  corsconfiguration config = new corsconfiguration();

  config.addallowedorigin( "http://domain1.com" );

  config.addallowedorigin( "http://domain2.com" );

  config.addallowedheader( "*" );

  config.addallowedmethod( "get, post, put, head, patch, delete, options, trace" );

  config.setallowcredentials( true );

  config.setmaxage(72000l);

  // cors 配置对所有接口都有效

  source.registercorsconfiguration( "/**" , config);

  filterregistrationbean<corsfilter> bean = new filterregistrationbean<>( new corsfilter(source));

  bean.setorder( 0 );

  return bean;

}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

原文链接:https://segmentfault.com/a/1190000017823645

查看更多关于Spring 跨域配置请求详解的详细内容...

  阅读:9次