Spring Oauth2中的CORS错误 [英] CORS error in Spring Oauth2

查看:76
本文介绍了Spring Oauth2中的CORS错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm using Spring security and Oauth2. But I'm new to Spring Oauth2, I Got the CORS error when front-end attends to access resource.

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

I'm using the below filter to allow other domains to access the resource:

@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中使用公共资源。

I wrote the below code to allow public resource in my 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。

For Oauth2, the below codes is for protecting user's resource in my 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个声誉来发布图像,因此我在此处粘贴了链接)

When I open the index.html file in the browser, like following:(Sorry I don't have at least 10 reputation to post images, so I paste links here)

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

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

it successfully get the public data, that means other domains are allowed to access "/public/**" data.

但是它无法获取 / user / **数据(受Oauth2保护)。它给了我以下错误,提示跨域请求已阻止。

But it failed to get "/user/**" data (protected by Oauth2). It gives me below error says "Cross-Origin Request Blocked".

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

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

When I move the front-end files to the same domain of the Spring server. It works fine to get both "public" and "user" data as below:

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

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

The front-end and Back-end should be separated. But the CORS is blocked to access projected data. Can anyone give me some suggestions? Thanks very much. I'm guessing the filter is not working on Oauth2? still spend a lot of time on looking for solutions.

推荐答案

@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() {
    }

}

这篇关于Spring Oauth2中的CORS错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆