背景

系统之前为一个单页应用提供过Rest接口,部署时这个单页应用与系统不在同一域内,出现跨域无法访问的问题。Spring 从 4.2 版本开始提供了@CrossOrigin注解,让这个问题的解决变得非常简单。

实现一

首先看下@CrossOrigin的源码(删掉了开头的部分注释):

package org.springframework.web.bind.annotation;

import java.lang.annotation.Documented;

import java.lang.annotation.ElementType;

import java.lang.annotation.Retention;

import java.lang.annotation.RetentionPolicy;

import java.lang.annotation.Target;

import org.springframework.core.annotation.AliasFor;

import org.springframework.web.cors.CorsConfiguration;

/**

* @author Russell Allen

* @author Sebastien Deleuze

* @author Sam Brannen

* @since 4.2

*/

@Target({ ElementType.METHOD, ElementType.TYPE })

@Retention(RetentionPolicy.RUNTIME)

@Documented

public @interface CrossOrigin {

/**

* @deprecated as of Spring 4.3.4, in favor of using {@link CorsConfiguration#applyPermitDefaultValues}

*/

@Deprecated

String[] DEFAULT_ORIGINS = { "*" };

/**

* @deprecated as of Spring 4.3.4, in favor of using {@link CorsConfiguration#applyPermitDefaultValues}

*/

@Deprecated

String[] DEFAULT_ALLOWED_HEADERS = { "*" };

/**

* @deprecated as of Spring 4.3.4, in favor of using {@link CorsConfiguration#applyPermitDefaultValues}

*/

@Deprecated

boolean DEFAULT_ALLOW_CREDENTIALS = true;

/**

* @deprecated as of Spring 4.3.4, in favor of using {@link CorsConfiguration#applyPermitDefaultValues}

*/

@Deprecated

long DEFAULT_MAX_AGE = 1800;

/**

* Alias for {@link #origins}.

*/

@AliasFor("origins")

String[] value() default {};

/**

* List of allowed origins, e.g. {@code "http://domain1.com"}.

*

These values are placed in the {@code Access-Control-Allow-Origin}

* header of both the pre-flight response and the actual response.

* {@code "*"} means that all origins are allowed.

*

If undefined, all origins are allowed.

* @see #value

*/

@AliasFor("value")

String[] origins() default {};

/**

* List of request headers that can be used during the actual request.

*

This property controls the value of the pre-flight response's

* {@code Access-Control-Allow-Headers} header.

* {@code "*"} means that all headers requested by the client are allowed.

*

If undefined, all requested headers are allowed.

*/

String[] allowedHeaders() default {};

/**

* List of response headers that the user-agent will allow the client to access.

*

This property controls the value of actual response's

* {@code Access-Control-Expose-Headers} header.

*

If undefined, an empty exposed header list is used.

*/

String[] exposedHeaders() default {};

/**

* List of supported HTTP request methods, e.g.

* {@code "{RequestMethod.GET, RequestMethod.POST}"}.

*

Methods specified here override those specified via {@code RequestMapping}.

*

If undefined, methods defined by {@link RequestMapping} annotation

* are used.

*/

RequestMethod[] methods() default {};

/**

* Whether the browser should include any cookies associated with the

* domain of the request being annotated.

*

Set to {@code "false"} if such cookies should not included.

* An empty string ({@code ""}) means undefined.

* {@code "true"} means that the pre-flight response will include the header

* {@code Access-Control-Allow-Credentials=true}.

*

If undefined, credentials are allowed.

*/

String allowCredentials() default "";

/**

* The maximum age (in seconds) of the cache duration for pre-flight responses.

*

This property controls the value of the {@code Access-Control-Max-Age}

* header in the pre-flight response.

*

Setting this to a reasonable value can reduce the number of pre-flight

* request/response interactions required by the browser.

* A negative value means undefined.

*

If undefined, max age is set to {@code 1800} seconds (i.e., 30 minutes).

*/

long maxAge() default -1;

}

从上面源码中可以看到,@CrossOrigin注解支持用于类和方法,访问IP默认为不限制,预检请求的有效期默认为1800秒,所以如不需指定IP和有效期,直接给需要支持跨域的类或方法添加注解即可:

@CrossOrigin

public JSONObject myMethod(...) {

...

}

但是事情肯定不会这么简单。。。

实现二

真正的需求是要通过配置文件配置IP白名单,白名单内允许跨域访问。然鹅,由于注解的参数无法动态赋值,IP地址这种参数也不能硬编码,所以@CrossOrigin就被我无情的抛弃了,转而通过Filter来实现:

import org.springframework.beans.factory.annotation.Value;

import org.springframework.boot.web.servlet.ServletComponentScan;

import org.springframework.stereotype.Component;

import javax.servlet.Filter;

import javax.servlet.FilterChain;

import javax.servlet.FilterConfig;

import javax.servlet.ServletException;

import javax.servlet.ServletRequest;

import javax.servlet.ServletResponse;

import javax.servlet.annotation.WebFilter;

import javax.servlet.http.HttpServletResponse;

import java.io.IOException;

@Component

@ServletComponentScan

@WebFilter(urlPatterns = "/*", filterName = "domainFilter")

public class DomainFilter implements Filter {

@Value("${allow-origin}")

private String domain;

@Override

public void init(FilterConfig filterConfig) throws ServletException {

}

@Override

public void doFilter(ServletRequest servletRequest,

ServletResponse servletResponse, FilterChain filterChain)

throws IOException, ServletException {

HttpServletResponse response = (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", "3600");

response.setHeader("Access-Control-Allow-Headers", "x-requested-with");

filterChain.doFilter(servletRequest, servletResponse);

}

@Override

public void destroy() {

}

}

在本类添加@ServletComponentScan注解,或在Spring Boot启动类添加注解并配置参数覆盖到本类路径,即可生效。

别忘了在配置文件中添加配置项:

allow-origin=10.110.16.151

java 接口 白名单,SpringBoot HTTP接口跨域调用及白名单实现相关推荐

  1. webapi做为后端接口时在跨域调用时的注意点

    比如一个典型的前端跨域调用: $.ajax({ url: url, data: params, dataType: 'jsonp', jsonpCallback:'jsonpcall', conten ...

  2. js跨域调用php接口,php的json格式和js跨域调用的代码

    function jsontest() { var json = [{'username':'crystal','userage':'20'},{'username':'candy','userage ...

  3. 记一次SpringBoot解决CROS跨域问题(CROS)

    记一次SpringBoot解决CROS跨域问题(CROS) 使用注解@CrossOrigin(局部跨域 后端创建注入切面 @Target({ElementType.TYPE, ElementType. ...

  4. 解决方案:SpringBoot分布式项目跨域

    解决方案:SpringBoot分布式项目跨域 场景: web端:localhost:8001 后台user服务:localhost:9001 请求:web端请求 后台user服务,报跨域异常 异常信息 ...

  5. SpringBoot2.1.5 (22)--- SpringBoot设置支持跨域请求

    SpringBoot2.1.5 (22)--- SpringBoot设置支持跨域请求 现代浏览器处于安全的考虑,在http/https请求时必须遵守同源策略,否则即使跨域的http/https 请求, ...

  6. java jquery jsonp 跨域_Jquery跨域调用(JSONP)遇到error问题的解决

    之前Jquery的跨域调用一直没有解决,不知道为什么老是执行error里的语句,今天花了点时间研究了一下,终于把问题解决了. 关键的地方是返回的字符串,返回的字符串必须包含jsonp的回调函数名称,而 ...

  7. Springboot中关于跨域问题的一种解决方法

    Springboot中关于跨域问题的一种解决方法 参考文章: (1)Springboot中关于跨域问题的一种解决方法 (2)https://www.cnblogs.com/zishu/p/107272 ...

  8. AJAX 跨域调用和 Java 跨域 发送请求

    AJAX 跨域调用 前台代码: Html代码   <script type="text/javascript" src="jquery-1.7.2.min.js&q ...

  9. 随笔-springBoot配置全局跨域

    随笔-springBoot配置全局跨域 本文参考链接: 前端看视频学习vue使用axios进行Ajax请求,视频中使用nodemon创建的node-server,弄了半天一直说跨域.为了不浪费时间直接 ...

最新文章

  1. 【java新】Optional pk 空指针
  2. IOS上传代码到CocoaPods并通过Pod下载
  3. 朋友,别告诉我你懂分布式事务!
  4. 样本距离计算、向量范数、矩阵范数
  5. NumPy之:标量scalars
  6. c++中创建类型测试
  7. (代码篇)从基础文件IO说起虚拟内存,内存文件映射,零拷贝
  8. 创建一个简单的数据库
  9. 2017-9-19Linux基础知识(2)
  10. 餐饮管理系统开发源码
  11. spfa算法的python实现
  12. MSDP RPF检测
  13. 新浪微博开放平台接入
  14. 在Azure的云服务器上搭建个人网站
  15. 乐理小课堂——自然/和声/旋律大调的调式音阶
  16. 总结了一套比较新的面试题挺全面的,多方面都有涉及到
  17. python-->with-上下文管理器
  18. 读《微波工程(第三版)》笔记 (10:终端接负载的无耗传输线)
  19. 一个完整推荐系统的设计实现
  20. Non-local Neural Networks论文理解

热门文章

  1. python自学行吗-零基础可以学会python吗?python好学吗?
  2. 济南python工资一般多少-Python火到天际,可是为啥找工作这么难?
  3. python编程例子-Python面向对象编程 - 类和实例
  4. python怎么读程序-python怎么读sql数据?
  5. 自学python免费教材-Python 有哪些入门学习方法和值得推荐的经典教材?
  6. 用python画玫瑰花-使用Python画一朵玫瑰花
  7. 微鲸科大讯飞、出门问问合作 TA的语音功能怎么样?
  8. 语音识别已逐渐普及 搜狗讯飞各具特色
  9. 科大讯飞独家Founding赞助国际语音顶会,14篇论文被收录
  10. 解决浏览器中点击input输入框时,placeholder的值不消失的方法