gf-huanchupk / SpringBootLearning

Spring Boot learning process
902 stars 650 forks source link

关于【springboot-security-oauth2 】项目的拦截器问题 #7

Open LiHuiNeng opened 4 years ago

LiHuiNeng commented 4 years ago

下载demo,运行跑完之后发现有一个问题,想请教一下。 1.带上token请求,执行到MyFilterSecurityInterceptor的doFilter方法。 HelloController控制器会先执行一次返回,得到正确结果。 image

2.之后该链路会继续调用,然后又再次返回到HelloController控制器,又得到一次返回。 image image 请教:如果只想得到一次返回结果该如何做呢? 谢谢!

musicguoke commented 2 years ago

@LiHuiNeng hi,Here's how I solved it.

@Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        if (!request.getRequestURI().equals("/oauth/token")) {
            FilterInvocation fi = new FilterInvocation(servletRequest, servletResponse, filterChain);
            invoke(fi);
        } else {
            HttpServletResponse response = (HttpServletResponse) servletResponse;
            response.setHeader("Access-Control-Allow-Origin", "*");
            response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
            response.setHeader("Access-Control-Allow-Headers", ":x-requested-with,content-type");
            filterChain.doFilter(servletRequest, servletResponse);
        }
    }