Webapp和移动应用程序使用的Spring API

时间:2017-08-30 10:52:44

标签: spring-boot mobile ionic-framework spring-security cors

我使用Angular 2开发了一个web应用程序,并使用Springboot开发了Rest API。

Mme Michu ---> WebApp (Angular 2 - Known origin) ---> API (Springboot CORS)

我在webapp和API之间配置了CORS,它运行正常。

以下是我的CORSFilter的实现方式

@Order(Ordered.HIGHEST_PRECEDENCE)
public class SimpleCORSFilter implements Filter{

public SimpleCORSFilter () {
    super();
}

@Autowired
private Environment environment;

private String[] acao;

@Override
public final void doFilter(final ServletRequest req, final ServletResponse res, final FilterChain chain) throws IOException, ServletException {

    acao = environment.getProperty("access-control-allow-origin").split(",");

    final HttpServletResponse response = (HttpServletResponse) res;
    final HttpServletRequest request = (HttpServletRequest) req;

    String origin = request.getHeader("Origin");

    response.setHeader("Access-Control-Allow-Origin", Arrays.asList(acao).contains(origin)?origin:"" );

    // without this header jquery.ajax calls returns 401 even after successful login and SSESSIONID being succesfully stored.
    response.setHeader("Access-Control-Allow-Credentials", "true");

    response.setHeader("Access-Control-Allow-Methods", "POST, PUT, GET, OPTIONS, DELETE");
    response.setHeader("Access-Control-Max-Age", "3600");
    response.setHeader("Access-Control-Allow-Headers", "X-Requested-With, Authorization, Origin, Content-Type, Version");
    response.setHeader("Access-Control-Expose-Headers", "X-Requested-With, Authorization, Origin, Content-Type");


    if(!request.getMethod().equals("OPTIONS")) {
        chain.doFilter(request, response);
    }
}

@Override
public void destroy() {

}

@Override
public void init(FilterConfig filterConfig) throws ServletException {
    acao = environment.getProperty("access-control-allow-origin").split(",");
}

}

问题在于我需要一个新的移动应用程序(使用离子开发)来与API进行交互。

Mme Michu --> MobileApp (Unknown origin) ---> API (Springboot CORS)

CORS政策会阻止来自移动应用的请求吗? 我如何授权来自移动应用程序的请求,因为我无法知道“来源”的来源。移动应用程序?

欢迎任何建议......

1 个答案:

答案 0 :(得分:1)

原点是向api发出请求的域名,如果您的webapp的域名是example.com,请求将以example.com作为来源。当资源因源而被阻止时,它是一个阻止响应的客户端安全机制(服务器不知道它)。你不知道Ionic是如何工作的,但我认为它没有实现这种机制(可能除了渐进的Web应用程序)。

服务器负责报告允许的来源。 Web浏览器负责强制执行仅从允许的域发送请求。