1

详细信息: 我正在使用 spring boot oauth2 资源服务器,即使在尝试了不同的方法来过滤它之后,它也会给我 CORS。

我的代码看起来如何?

它是一个简单的资源服务器,带有 Spring Bootspring-cloud-starter-oauth2spring-cloud-starter-security两个主要依赖项。

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

@CrossOrigin(origins = "*", maxAge = 3600, allowedHeaders = "*")
@RestController
@RequestMapping("/api/v1")
@EnableResourceServer

这是我尝试解决此问题的方法:

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

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

}
4

2 回答 2

1

我有同样的问题,这就是解决方案。

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);
}

}

public class CorsFilterCustom extends OncePerRequestFilter {

@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
        throws ServletException, IOException {
    response.setHeader("Access-Control-Allow-Origin", "*");
    response.setHeader("Access-Control-Allow-Credentials", "true");
    response.setHeader("Access-Control-Allow-Methods",
            "ACL, CANCELUPLOAD, CHECKIN, CHECKOUT, COPY, DELETE, GET, HEAD, LOCK, MKCALENDAR, MKCOL, MOVE, OPTIONS, POST, PROPFIND, PROPPATCH, PUT, REPORT, SEARCH, UNCHECKOUT, UNLOCK, UPDATE, VERSION-CONTROL");
    response.setHeader("Access-Control-Max-Age", "3600");
    response.setHeader("Access-Control-Allow-Headers",
            "Origin, X-Requested-With, Content-Type, Accept, Key, Authorization");

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

}

public class AuthorizationServerCustom implements AuthorizationServerConfigurer {

@Override
public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
    security.checkTokenAccess("isAuthenticated()");
}

@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
    endpoints.tokenStore(tokenStore()).authenticationManager(authenticationManager);
}

}

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);
}

}

于 2020-08-06T15:47:06.560 回答
0

您可以通过添加具有不同变体的配置类来配置 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();
  }
}
于 2020-08-06T15:22:13.933 回答