★【Core Moshow 郑锴】★

POWERED BY MOSHOW .... CORE iWN , WE ARE LOADING THE DREAM!

Spring-Cloud-Zuul支持获取JWT的Authorization响应头

背景

最近公司项目用到jwt,再前后端配合的时候出现了一点问题,前端vuejs无法获取后盾spring-cloud-zuul传来的响应头。

原因

在默认的请求上, 浏览器只能访问以下响应头:

  • Cache-Control
  • Content-Language
  • Content-Type
  • Expires
  • Last-Modified
  • Pragma

解决方案

如果想让浏览器能访问到其他的 响应头的话 需要在服务器上设置 Access-Control-Expose-Headers为Authorization,则前端可以成功获取Authorization,完成JWT认证

Access-Control-Expose-Headers : ‘Authorization’

@Configuration
public class GateWayCorsConfig {
    @Bean
    public CorsFilter corsFilter() {
        final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        final CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.addAllowedHeader("*");
        corsConfiguration.addAllowedOrigin("*");
        corsConfiguration.addAllowedMethod("*");
        //↓核心代码
        corsConfiguration.addExposedHeader("Authorization");
        source.registerCorsConfiguration("/**", corsConfiguration);
        return new CorsFilter(source);
    }
}

或者

@Component  
public class CorsFilter implements Filter {  
    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {  
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;  
        //↓核心代码
        response.setHeader("Access-Control-Expose-Headers", "Authorization");  
        response.setHeader("Access-Control-Allow-Origin", "*");  
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, PUT, GET");  
        response.setHeader("Access-Control-Max-Age", "3600");  
        response.setHeader("Access-Control-Allow-Headers", "x-requested-with"); 
        chain.doFilter(req, res);  
    }  
    @Override
    public void init(FilterConfig filterConfig) {}  
    @Override
    public void destroy() {}  
}  
阅读更多
个人分类: Spring
所属专栏: SpringBoot2
想对作者说点什么? 我来说一句

Zuul的高可用

Zuul

gaowenhui2008 gaowenhui2008

2017-09-12 16:21:20

阅读数:585

没有更多推荐了,返回首页

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭