java接口白名单,SpringBootHTTP接口跨域调用及白名单实现_第1页
java接口白名单,SpringBootHTTP接口跨域调用及白名单实现_第2页
免费预览已结束,剩余1页可下载查看

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

java,SpringBootHTTP接⼝跨域调⽤及⽩名单实现背景系统之前为⼀个单页应⽤提供过Rest接⼝,部署时这个单页应⽤与系统不在同⼀域内,出现跨域⽆法访问的问题。Spring从4.2版本开始提供了@CrossOrigin注解,让这个问题的解决变得⾮常简单。实现⼀⾸先看下@CrossOrigin的源码(删掉了开头的部分注释):packageorg.springframework.web.bind.annotation;importjava.lang.annotation.Documented;importjava.lang.annotation.ElementType;importjava.lang.annotation.Retention;importjava.lang.annotation.RetentionPolicy;importjava.lang.annotation.Target;importorg.springframework.core.annotation.AliasFor;importorg.springframework.web.cors.CorsConfiguration;/***@authorRussellAllen*@authorSebastienDeleuze*@authorSamBrannen*@since4.2*/@Target({ElementType.METHOD,ElementType.TYPE})@Retention(RetentionPolicy.RUNTIME)@Documentedpublic@interfaceCrossOrigin{/***@deprecatedasofSpring4.3.4,infavorofusing{@linkCorsConfiguration#applyPermitDefaultValues}*/@DeprecatedString[]DEFAULT_ORIGINS={"*"};/***@deprecatedasofSpring4.3.4,infavorofusing{@linkCorsConfiguration#applyPermitDefaultValues}*/@DeprecatedString[]DEFAULT_ALLOWED_HEADERS={"*"};/***@deprecatedasofSpring4.3.4,infavorofusing{@linkCorsConfiguration#applyPermitDefaultValues}*/@DeprecatedbooleanDEFAULT_ALLOW_CREDENTIALS=true;/***@deprecatedasofSpring4.3.4,infavorofusing{@linkCorsConfiguration#applyPermitDefaultValues}*/@DeprecatedlongDEFAULT_MAX_AGE=1800;/***Aliasfor{@link#origins}.*/@AliasFor("origins")String[]value()default{};/***Listofallowedorigins,e.g.{@code""}.*Thesevaluesareplacedinthe{@codeAccess-Control-Allow-Origin}*headerofboththepre-flightresponseandtheactualresponse.*{@code"*"}meansthatalloriginsareallowed.*Ifundefined,alloriginsareallowed.*@see#value*/@AliasFor("value")String[]origins()default{};/***Listofrequestheadersthatcanbeusedduringtheactualrequest.*Thispropertycontrolsthevalueofthepre-flightresponse's*{@codeAccess-Control-Allow-Headers}header.*{@code"*"}meansthatallheadersrequestedbytheclientareallowed.*Ifundefined,allrequestedheadersareallowed.*/String[]allowedHeaders()default{};/***Listofresponseheadersthattheuser-agentwillallowtheclienttoaccess.*Thispropertycontrolsthevalueofactualresponse's*{@codeAccess-Control-Expose-Headers}header.*Ifundefined,anemptyexposedheaderlistisused.*/String[]exposedHeaders()default{};/***ListofsupportedHTTPrequestmethods,e.g.*{@code"{RequestMethod.GET,RequestMethod.POST}"}.*Methodsspecifiedhereoverridethosespecifiedvia{@codeRequestMapping}.*Ifundefined,methodsdefinedby{@linkRequestMapping}annotation*areused.*/RequestMethod[]methods()default{};/***Whetherthebrowsershouldincludeanycookiesassociatedwiththe*domainoftherequestbeingannotated.*Setto{@code"false"}ifsuchcookiesshouldnotincluded.undefined*Anemptystring({@code""})means.*{@code"true"}meansthatthepre-flightresponsewillincludetheheader*{@codeAccess-Control-Allow-Credentials=true}.*Ifundefined,credentialsareallowed.*/StringallowCredentials()default"";/***Themaximumage(inseconds)ofthecachedurationforpre-flightresponses.*Thispropertycontrolsthevalueofthe{@codeAccess-Control-Max-Age}*headerinthepre-flightresponse.*Settingthistoareasonablevaluecanreducethenumberofpre-flight*request/responseinteractionsrequiredbythebrowser.undefined*Anegativevaluemeans*.Ifundefined,maxageissetto{@code1800}seconds(i.e.,30minutes).*/longmaxAge()default-1;}从上⾯源码中可以看到,@CrossOrigin注解⽀持⽤于类和⽅法,访问IP默认为不限制,预检请求的有效期默认为1800秒,所以如不需指定IP和有效期,直接给需要⽀持跨域的类或⽅法添加注解即可:@CrossOriginpublicJSONObjectmyMethod(...){...}但是事情肯定不会这么简单。。。实现⼆真正的需求是要通过配置⽂件配置IP⽩名单,⽩名单内允许跨域访问。然鹅,由于注解的参数⽆法动态赋值,IP地址这种参数也不能硬编码,所以@CrossOrigin就被我⽆情的抛弃了,转⽽通过Filter来实现:importorg.springframework.beans.factory.annotation.Value;importorg.springframework.boot.web.servlet.ServletComponentScan;importorg.springframework.stereotype.Component;importjavax.servlet.Filter;importjavax.servlet.FilterChain;importjavax.servlet.FilterConfig;importjavax.servlet.ServletException;importjavax.servlet.ServletRequest;importjavax.servlet.ServletResponse;importjavax.servlet.annotation.WebFilter;importjavax.servlet.http.HttpServletResponse;importjava.io.IOException;@Component@ServletComponentScan@WebFilter(urlPatterns="/*",filterName="domainFilter")publicclassDomainFilterimplementsFilter{@Value("${allow-origin}")privateStringdomain;@Overridepublicvoidinit(FilterConfigfilterConfig)throwsServletException{}@OverridepublicvoiddoFilter(ServletRequestservletRequest,ServletResponseservletResponse,FilterChainfilterChain)throwsIOException,ServletException{HttpServletResponseresponse=(HttpServletResponse)servletResponse;if(!domain.startsWith("http://")&&!domain.startsWith("https://")){domain="http://"+domain;}response.setHeader("Access-Control-Allow-Origin",domain);response.setHeader("Access-Control-Allow-Methods","POST,GET,OPTIONS,DELETE");response.setHeader("Access-Control-Max-Age",

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论