请求的资源上不存在“Access-Control-Allow-Origin”标头,响应的 HTTP 状态代码为 401

2023-12-24

我一直在实现 Spring(4.3) Restful 应用程序,它具有基于 spring security 和 oauth(2) 的配置。实现这些配置后,我通过邮递员测试了我的其余 api 调用,一切都很好,但我的客户端只是 jquery 或 ajax。当我尝试调用 oauth 令牌时,它显示“请求的资源上不存在“Access-Control-Allow-Origin”标头。Origin 'http://本地主机:8080 http://localhost:8080'因此不允许访问”错误,我也配置了cors启用配置。但我不知道我错过了哪一部分,请帮助我。在谷歌上有很多建议之后,我也尝试了过滤器方法以及spring安全配置但仍然遇到同样的错误。

我的服务器代码

@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {

  @Override
  public void addCorsMappings(CorsRegistry registry) {
    registry.addMapping("/**")
            .allowedMethods("HEAD", "GET", "PUT", "POST", "DELETE", 
            "PATCH","OPTIONS"));
 }
}

=========================================

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
@Order(Ordered.HIGHEST_PRECEDENCE)
protected void configure(HttpSecurity http) throws Exception {
    http.cors().and()
    .sessionManagement()
    .sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
    //.csrf().disable()
    .authorizeRequests()
            .antMatchers("/register").permitAll()
            .antMatchers("/contact").permitAll()
            .antMatchers("/signup").permitAll()
            .antMatchers("/oauth/**").permitAll()
            .antMatchers(HttpMethod.OPTIONS,"*").permitAll()
            .anyRequest().authenticated().and()

            .httpBasic();
    // .realmName("CRM_REALM");

}

=============================================

@Bean
public CorsConfigurationSource corsConfigurationSource() {
    final CorsConfiguration configuration = new CorsConfiguration();
    configuration.setAllowedOrigins(Arrays.asList("*"));
    configuration.setAllowedMethods(Arrays.asList("HEAD",
            "GET", "POST", "PUT", "DELETE", "PATCH","OPTIONS")));
    // setAllowCredentials(true) is important, otherwise:
    // The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'.
    configuration.setAllowCredentials(true);
    // setAllowedHeaders is important! Without it, OPTIONS preflight request
    // will fail with 403 Invalid CORS request
    configuration.setAllowedHeaders(Arrays.asList("Authorization", "Cache-Control", "Content-Type"));
    final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    source.registerCorsConfiguration("/**", configuration);
    return source;
}

客户端代码

 var settings = {
          "async": true,
          "crossDomain": true,
          "url": "http://10.10.1.13:8080/OauthCrud/oauth/token",
          "method": "POST",
          "headers": {
            "authorization": "Basic b2F1dGhDcnVkOm9hdXRoU3VwZXJTZWNyZXQ=",
            "content-type": "application/x-www-form-urlencoded",
            "cache-control": "no-cache",
            "postman-token": "22b603e4-bf59-b722-d758-f51a1fe1a1d4"
          },
          "data": {
            "username": "rama",
            "password": "rama",
            "grant_type": "password"
          }
        }

        $.ajax(settings).done(function (response) {
          console.log(response);
        });

Error:


None

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

请求的资源上不存在“Access-Control-Allow-Origin”标头,响应的 HTTP 状态代码为 401 的相关文章

随机推荐