繁体   English   中英

Spring Oauth2中的CORS错误

[英]CORS error in Spring Oauth2

我正在使用Spring安全性和Oauth2。 但是我是Spring Oauth2的新手,前端参与访问资源时出现CORS错误。

我正在使用以下过滤器,以允许其他域访问资源:

@Component
@Order(Integer.MAX_VALUE)
public class SimpleCORSFilter implements Filter {

    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) res;
        response.setHeader("Access-Control-Allow-Credentials", "True");
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization");
        chain.doFilter(req, res);
    }


    public void init(FilterConfig filterConfig) {}
    public void destroy() {}

}

我编写了以下代码,以允许在SecurityConfiguration.java中使用公共资源。

@Override
protected void configure(HttpSecurity http) throws Exception {
             http
        .authorizeRequests().antMatchers("/social/facebook/**","/register/**","/public/**").permitAll().and()
        .authorizeRequests().antMatchers("/user/**").hasRole("USER").and()           
        .exceptionHandling()
            .accessDeniedPage("/login.jsp?authorization_error=true")
            .and()
        .csrf()
            .requireCsrfProtectionMatcher(new AntPathRequestMatcher("/oauth/authorize")).disable();

}

对于Oauth2,以下代码用于保护我的OAuth2ServerConfig.java中的用户资源。

@Override
    public void configure(HttpSecurity http) throws Exception {
        http

            .requestMatchers().antMatchers("/user/**")
        .and()
            .authorizeRequests()
            .antMatchers("/user/**").access("#oauth2.hasScope('read')")
                .regexMatchers(HttpMethod.DELETE, "/oauth/users/([^/].*?)/tokens/.*")
                    .access("#oauth2.clientHasRole('ROLE_CLIENT') and (hasRole('ROLE_USER') or #oauth2.isClient()) and #oauth2.hasScope('write')")
                .regexMatchers(HttpMethod.GET, "/oauth/clients/([^/].*?)/users/.*")
                    .access("#oauth2.clientHasRole('ROLE_CLIENT') and (hasRole('ROLE_USER') or #oauth2.isClient()) and #oauth2.hasScope('read')")
                .regexMatchers(HttpMethod.GET, "/oauth/clients/.*")
                    .access("#oauth2.clientHasRole('ROLE_CLIENT') and #oauth2.isClient() and #oauth2.hasScope('read')");
    }

当我在浏览器中打开index.html文件时,如下所示:(很抱歉,我没有至少10个声誉来发布图像,因此我在此处粘贴了链接)

http://i.stack.imgur.com/yQKJM.png

它成功获取了公共数据,这意味着允许其他域访问“ / public / **”数据。

但是它无法获取“ / user / **”数据(受Oauth2保护)。 它给我下面的错误说:“跨源请求被阻止”。

http://i.stack.imgur.com/XIVx1.png

当我将前端文件移动到Spring服务器的相同域时。 可以同时获取“公开”和“用户”数据,如下所示:

http://i.stack.imgur.com/Q2n7F.png

前端和后端应分开。 但是CORS被阻止访问投影数据。 谁能给我一些建议? 非常感谢。 我猜想过滤器在Oauth2上不起作用? 仍然花费大量时间寻找解决方案。

@Component
@Order(Ordered.HIGHEST_PRECEDENCE)

public class SimpleCORSFilter implements Filter {

    @Override
    public void init(FilterConfig fc) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp,
                         FilterChain chain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) resp;
        HttpServletRequest request = (HttpServletRequest) req;
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "PATCH,POST,GET,OPTIONS,DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "x-requested-with, authorization, Content-Type, Authorization, credential, X-XSRF-TOKEN");

        if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
            response.setStatus(HttpServletResponse.SC_OK);
        } else {
            chain.doFilter(req, resp);
        }

    }

    @Override
    public void destroy() {
    }

}

我将标头添加到端点

@Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints)
            throws Exception {

        endpoints.addInterceptor(new HandlerInterceptorAdapter() {
            @Override
            public boolean preHandle(HttpServletRequest hsr, HttpServletResponse rs, Object o) throws Exception {
                rs.setHeader("Access-Control-Allow-Origin", "*");
                rs.setHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS");
                rs.setHeader("Access-Control-Max-Age", "3600");
                rs.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization");
                return true;
            }
        });


    }

首先调用OAuth过滤器,并引发Exception(已阻止该异常运行您的CORS过滤器)。

您必须添加此注释

@Order(Ordered.HIGHEST_PRECEDENCE)

到您的CORS过滤器。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM