美文网首页
springboot 在整合shiro后,跨域就失效了。

springboot 在整合shiro后,跨域就失效了。

作者: 虾米咬小米 | 来源:发表于2020-12-23 14:44 被阅读0次

原springboot 解决跨域问题

package com.daoshu.involved.shared.core.configurer;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
* @Description: 解决跨域问题
* @Author: zhaopf@mti-sh.cn
* @Date: 2019/4/18 19:09
*/
@Configuration
public class CorsConfig implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("*")
                .allowCredentials(true)
                .allowedMethods("GET", "POST", "DELETE", "PUT","PATCH")
                .maxAge(3600);
    }
}

使用 tomcat 中的 Filter的方式解决跨域

/**
 * @author zhaopf@mti-sh.cn
 * @Description TODO HttpServletResponse HttpServletResponse 编码全局设置  and 跨域设置
 *
 *
 * springboot 中都能解决跨域的问题,但是在整合shiro后,跨域就失效了。
 *
 * 原因是:shiro的过滤器会在跨域处理之前执行,这就导致未允许跨域的请求先到达shiro过滤器,这样就会出现跨域错误。
 *
 * 解决方案
 * 使用 tomcat 中的 Filter的方式解决跨域
 *
 * @createTime 2020年12月18日
 */

@Configuration
public class CorsEncodingFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
        response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, If-Modified-Since, x-token");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.addHeader("Access-Control-Allow-Credentials", "true");

        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        filterChain.doFilter(request , response);
    }
    @Override
    public void destroy() {
    }
}

相关文章

网友评论

      本文标题:springboot 在整合shiro后,跨域就失效了。

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