Java 如何在Spring Boot Oauth2资源服务器中使用密码授权来处理CORS

Java 如何在Spring Boot Oauth2资源服务器中使用密码授权来处理CORS,java,spring-boot,oauth-2.0,cors,cloud-security,Java,Spring Boot,Oauth 2.0,Cors,Cloud Security,详细信息: 我使用的是SpringBootOAuth2资源服务器,它给了我CORS,即使在尝试了不同的过滤方法之后 我的代码看起来怎么样? 它是一个简单的资源服务器,具有spring boot,其中spring-cloud-starter-oauth2和spring-cloud-starter-security作为两个主要依赖项 我已经使用java注释使其成为一个资源服务器: @CrossOrigin(origins = "*", maxAge = 3600, allowed

详细信息: 我使用的是SpringBootOAuth2资源服务器,它给了我CORS,即使在尝试了不同的过滤方法之后

我的代码看起来怎么样?

它是一个简单的资源服务器,具有spring boot,其中
spring-cloud-starter-oauth2
spring-cloud-starter-security
作为两个主要依赖项

我已经使用java注释使其成为一个资源服务器:

@CrossOrigin(origins = "*", maxAge = 3600, allowedHeaders = "*")
@RestController
@RequestMapping("/api/v1")
@EnableResourceServer
以下是我试图解决此问题的方法:

我尝试添加一个自定义过滤器,它可以跳过下面代码的进一步过滤器调用。在此之后,我得到了“在浏览器上的飞行前请求中不允许使用授权头”。将
CORS everyhere
扩展添加到我的浏览器后,我的请求成功

@EnableWebSecurity(debug = true)
@Order(Ordered.HIGHEST_PRECEDENCE)
public class WebSecurityConfig implements Filter {

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS, DELETE, PATCH");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
        response.setHeader("Access-Control-Expose-Headers", "Location");
        System.out.println(request.getMethod());
        System.out.println("-----------------");
        if(!request.getMethod().equals("OPTIONS")) {
            chain.doFilter(req, res);
        }
    }

    @Override
    public void init(FilterConfig filterConfig) {}

    @Override
    public void destroy() {}

}

您可以通过添加具有如下不同变体的配置类来配置cors

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

  @Override
  protected void configure(HttpSecurity http) throws Exception {
    CorsConfiguration config = new CorsConfiguration();
    config.setAllowedMethods(Collections.singletonList("*"));

    http.cors().configurationSource(request -> config);
  }
}
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

  @Override
  protected void configure(HttpSecurity http) throws Exception {
    http.cors().disable();
  }
}
或者像这样禁用

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

  @Override
  protected void configure(HttpSecurity http) throws Exception {
    CorsConfiguration config = new CorsConfiguration();
    config.setAllowedMethods(Collections.singletonList("*"));

    http.cors().configurationSource(request -> config);
  }
}
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

  @Override
  protected void configure(HttpSecurity http) throws Exception {
    http.cors().disable();
  }
}
我也有同样的问题 这就是决议

public class ResourceServerCustom extends ResourceServerConfigurerAdapter {

@Override
public void configure(HttpSecurity http) throws Exception {
    http.csrf().disable().cors().disable().authorizeRequests().antMatchers("/oauth/token/**").permitAll()
            .anyRequest().authenticated().and().exceptionHandling()
            .authenticationEntryPoint(new AuthExceptionEntryPoint());

    http.cors().configurationSource(request -> new CorsConfiguration().applyPermitDefaultValues());

}
}

和其他配置

public class WebSecurityCustom extends WebSecurityConfigurerAdapter {

public TokenStore tokenStore;

@Bean
@Override
protected AuthenticationManager authenticationManager() throws Exception {
    return super.authenticationManager();
}

@Override
public void configure(WebSecurity web) throws Exception {
    web.ignoring().antMatchers("/v2/api-docs", "/configuration/ui", "/swagger-resources/**",
            "/configuration/security", "/swagger-ui.html", "/webjars/**");
    web.ignoring().antMatchers(HttpMethod.OPTIONS);
}
}

}

}

公共类AuthExceptionEntryPoint实现AuthenticationEntryPoint{
@凌驾
公共无效开始(HttpServletRequest请求、HttpServletResponse响应、AuthenticationException arg2)
抛出ServletException、IOException{
final Map mapBodyException=新HashMap();
mapBodyException.put(“错误”,“来自AuthenticationEntryPoint的错误”);
mapBodyException.put(“消息”,“来自AuthenticationEntryPoint的消息”);
放置(“异常”,“我的堆栈跟踪异常”);
mapBodyException.put(“路径”,request.getServletPath());
mapBodyException.put(“timestamp”,(new Date()).getTime());
setContentType(“应用程序/json”);
response.setStatus(HttpServletResponse.SC_禁止);
最终ObjectMapper映射器=新ObjectMapper();
writeValue(response.getOutputStream(),mapBodyException);
}

}

公共类ResourceServerCustom扩展ResourceServerConfigurerAdapter{@Override public void configure(HttpSecurity http)引发异常{http.csrf().disable().cors().disable().authorizeRequests().antMatchers(“/oauth/token/**”).permitAll().anyRequest().authorized()和().exceptionHandling().authenticationEntryPoint(新建AuthExceptionEntryPoint());http.cors().configurationSource(请求->新建CorsConfiguration().applyPermitDefaultValues());}
public class AuthExceptionEntryPoint implements AuthenticationEntryPoint {

@Override
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException arg2)
        throws ServletException, IOException {
    final Map<String, Object> mapBodyException = new HashMap<>();

    mapBodyException.put("error", "Error from AuthenticationEntryPoint");
    mapBodyException.put("message", "Message from AuthenticationEntryPoint");
    mapBodyException.put("exception", "My stack trace exception");
    mapBodyException.put("path", request.getServletPath());
    mapBodyException.put("timestamp", (new Date()).getTime());

    response.setContentType("application/json");
    response.setStatus(HttpServletResponse.SC_FORBIDDEN);

    final ObjectMapper mapper = new ObjectMapper();
    mapper.writeValue(response.getOutputStream(), mapBodyException);
}