美文网首页
为Access-Control-Allow-Origin设置白名

为Access-Control-Allow-Origin设置白名

作者: 初心myp | 来源:发表于2019-07-22 16:25 被阅读0次

java代码实现

import org.apache.lucene.geo3d.Tools;
import org.springframework.beans.factory.annotation.Value;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;

/**
 * @FileName: WhiteFilter
 * @Description: 白名单过滤器
 * @author: <a href="">myp</a>
 * @create: 2019-07-19 18:04
 * @Copyright: (c) 2018年 北京柯莱特科技有限公司
 */
@WebFilter(filterName="whiteFilter",urlPatterns="/*")
public class WhiteFilter implements Filter {

    @Value("${xy.cors-white-list}")
    private String whiteList;


    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;

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

        response.setHeader("Access-Control-Allow-Origin", Arrays.asList(whiteList.split(",")).contains(origin) ? origin : "-");
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, PATCH, DELETE, PUT, OPTIONS");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "*");
        if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
            response.setStatus(HttpServletResponse.SC_OK);
        } else {
            chain.doFilter(req, res);
        }
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void destroy() {

    }
}

相关文章

网友评论

      本文标题:为Access-Control-Allow-Origin设置白名

      本文链接:https://www.haomeiwen.com/subject/fzpwlctx.html