当前位置: 首页 > 知识库问答 >
问题:

Spring security 4.2.3,OAUTH 2,/OAUTH/tokenendpoint,CORS不工作

终睿
2023-03-14

Angular 5应用程序需要登录用户。令牌请求发送到/oauth/Token。由于CORS,飞行前选项请求(由Chrome发送)失败。

我试图遵循Spring Security 4.2中的示例以及Stackoverflow上的各种问题和回复。

这是我的代码:

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

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

        http
        .cors().and()
        .csrf().disable()
            .anonymous().disable()
        .sessionManagement()
        .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
        .and()
        .authorizeRequests()
        .antMatchers("/signup").permitAll()
        .antMatchers("/oauth/token").permitAll()
        .antMatchers("/fapi/**").authenticated()
        .and()
        .httpBasic()
            .realmName("MY_REALM");
    }

    @Bean
    CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(Arrays.asList("http://example.com"));
        configuration.setAllowedMethods(Arrays.asList("HEAD", "GET", "PUT", "POST", "DELETE", "PATCH", "OPTIONS"));
        configuration.addAllowedHeader("*");
        configuration.setAllowCredentials(true);
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }
    ............
}

这是Chrome的请求

General Headers

Request URL: http://api.example.com/oauth/token
Request Method: OPTIONS
Status Code: 401 
Remote Address: 127.65.43.21:80
Referrer Policy: no-referrer-when-downgrade


Request headers

Accept: */*
Accept-Encoding: gzip, deflate
Accept-Language: en-US,en;q=0.9
Access-Control-Request-Headers: authorization
Access-Control-Request-Method: POST
Cache-Control: no-cache
Connection: keep-alive
Host: api.example.com
Origin: http://example.com
Pragma: no-cache
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.139 Safari/537.36

答复:

Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Content-Language: en
Content-Length: 1111
Content-Type: text/html;charset=utf-8
Date: Mon, 07 May 2018 03:23:15 GMT
Expires: 0
Pragma: no-cache
WWW-Authenticate: Basic realm="MY_REALM"
X-Content-Type-Options: nosniff
X-Frame-Options: DENY
X-XSS-Protection: 1; mode=block

控制台中的错误:

Failed to load http://api.example.com/oauth/token: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://example.com' is therefore not allowed access. The response had HTTP status code 401.

共有2个答案

刁跃
2023-03-14

代替您所做的,编写一个自定义cors过滤器,如下所示

@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class SimpleCorsFilter implements Filter {

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) res;
        HttpServletRequest request = (HttpServletRequest) req;
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, PUT");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "Origin, 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, res);
        }
        }

        @Override
        public void init(FilterConfig filterConfig) {
        }

        @Override
        public void destroy() {
        }
    }

并修改您的配置(HttpSecurity超文本传输协议)覆盖到

@Override
    protected void configure(HttpSecurity http) throws Exception {
        http
        .and()
        .csrf().disable()
            .anonymous().disable()
        .sessionManagement()
        .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
        .and()
        .authorizeRequests()
        .antMatchers("/signup").permitAll()
        .antMatchers("/oauth/token").permitAll()
        .antMatchers("/fapi/**").authenticated()
        .and()
        .httpBasic()
            .realmName("MY_REALM");
    }
怀飞扬
2023-03-14

我无法使用Spring提供的CorsFilter。

这里的工作很有帮助。

启用Oauth2时出现Spring security、cors错误

最终代码部分

@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
@WebFilter("/*")
public class SimpleCORSFilter implements Filter {

    public SimpleCORSFilter() {
    }

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

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp,
                         FilterChain chain) throws IOException, ServletException {

        System.out.println("doFilter");
        HttpServletResponse response = (HttpServletResponse) resp;
        HttpServletRequest request = (HttpServletRequest) req;
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, PUT");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "Origin, origin, 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() {
    }    
}

在安全配置中:

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers(HttpMethod.OPTIONS, "/oauth/token");
    }
    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http
      //.cors().and()
        .csrf().disable()
            .anonymous().disable()
        .sessionManagement()
        .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
        .and()
        .authorizeRequests()
        .antMatchers("/signup").permitAll()
        .antMatchers("/oauth/token").permitAll()
        .antMatchers("/fapi/**").authenticated()
        .and()
        .httpBasic()
            .realmName("MY_REALM");
    }

    /*
    @Bean
    CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(Arrays.asList("http://example.com"));
        configuration.setAllowedMethods(Arrays.asList("HEAD", "GET", "PUT", "POST", "DELETE", "PATCH", "OPTIONS"));
        configuration.addAllowedHeader("*");
        configuration.setAllowCredentials(true);
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }*/
    ............
}

我仍在等待一个使其与Spring Security的CorsFilter一起工作的示例。

 类似资料:
  • 这是我在使用Angular 1.5应用程序发出请求时Chrome控制台中得到的: XMLHttpRequest无法加载http://localhost:8080/api/oauth/token.对预检请求的响应没有通过权限改造检查:请求的资源上没有“访问控制允许起源”标头。因此不允许访问起源“http://localhost:8000”。响应的HTTP状态代码为401。 当我删除OAuth2配置时

  • 我使用AWS Cognito UI登录使用授权代码授予流,并成功获得授权代码。但是,当通过postman向oAuth2/令牌endpoint发出后请求时,获取405方法不允许出错 应用客户端设置在Cognito用户池中,应用秘密通过appclientid: appclientSecret作为Base64编码中的授权。

  • 我有一个奇怪的问题,每天我的AJAX请求一个网站不再工作。 我现在正在努力使它工作,但找不到问题。 这是我的JavaScript:基本上它非常简单,它检索ip adres并将其发送到存储它的站点。 在服务器上,我现在添加了这一项,以避免使用通配符 当我只使用 头('access-control-allow-origin:');我得到错误:Cross-Origin-request blocked:C

  • 当我们使用axios客户机从节点服务器访问API时,它总是运行以下错误:

  • 下面是配置。。。 我的后端是localhost:8080,前端是localhost:3000。后端的身份验证仅通过OAuth2处理。基本上,前端用户单击“使用Spotify登录”,会被重定向到处理OAuth2的后端,然后重定向回前端。所有后续请求都来自前端到后端。(前端位于Next.JS BTW中) 这是我的问题。。。 如果我没有经过身份验证,任何对我后端的请求都会抛出一个CORS错误。(如果我通

  • 我的服务器运行在localhost:8080(spring boot app)上,前端运行在localhost:3000(angular app)上。问题是我想从前端向后端服务器发出请求。我熟悉cors,但对我来说不起作用。我已将此添加到我的服务器: ,但我仍然得到 XMLHttpRequest无法加载http://localhost:8080/cars.请求被重定向到http://localho