Как мне обрабатывать CORS на сервере ресурсов Spring Boot Oauth2 с предоставлением пароля - PullRequest
0 голосов
/ 06 августа 2020

Подробности: Я использую сервер ресурсов oauth2 с весенней загрузкой, который дает мне CORS даже после попытки отфильтровать это разными способами.

Как выглядит мой код?

Это простой сервер ресурсов с весенней загрузкой с spring-cloud-starter-oauth2 и spring-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() {}

}

Ответы [ 2 ]

1 голос
/ 06 августа 2020

У меня была такая же проблема, и это было разрешение.

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

}

0 голосов
/ 06 августа 2020

Вы можете настроить 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();
  }
}
...