首页 > 解决方案 > 带有 Spring Boot 的 Ionic 3 中的 CORS 问题

问题描述

我在网络安全配置中启用 CORS:

@Configuration
@EnableWebSecurity
public class MyWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {

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

        http
                .cors().and()
                .csrf().disable()
                .authorizeRequests()
                .antMatchers( "/forms/**").permitAll()
                .antMatchers( "/member/login").permitAll()
                .antMatchers( "/member/signup").permitAll()
                .anyRequest().authenticated()
                .and().logout().logoutRequestMatcher(new AntPathRequestMatcher("/member/logout")).logoutSuccessHandler((new HttpStatusReturningLogoutSuccessHandler(HttpStatus.OK)))
                .and().requestCache().requestCache(new NullRequestCache());
    }

    @Bean
    public JsonUsernamePasswordAuthenticationFilter authenticationFilter() throws Exception {

    JsonUsernamePasswordAuthenticationFilter authenticationFilter = new JsonUsernamePasswordAuthenticationFilter();
    authenticationFilter.setAuthenticationSuccessHandler(authenticationSuccessHandler());
    authenticationFilter.setAuthenticationFailureHandler(authenticationFailureHandler());
    authenticationFilter.setAuthenticationManager(authenticationManagerBean());
    authenticationFilter.setFilterProcessesUrl("/member/login");
    authenticationFilter.setPasswordParameter("password");
    authenticationFilter.setUsernameParameter("email");
    authenticationFilter.setPostOnly(true);
    return authenticationFilter;
    }
}

并且JsonUsernamePasswordAuthenticationFilter

@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {

    if(CorsUtils.isPreFlightRequest(request) || request.getMethod().equals(HttpMethod.OPTIONS.name())) response.setHeader("Allow", HttpMethod.POST.name());

    if (this.postOnly && !request.getMethod().equals("POST")) {
        return null;
    } else {

        MemberLogin login = getAuthenticationRequest(request);

        if (login.getEmail() == null) login.setEmail("");
        if (login.getPassword() == null) login.setPassword("");

        UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(login.getEmail(), login.getPassword());
        setDetails(request, token);
        return getAuthenticationManager().authenticate(token);
    }
}

当我ionic cordova emulate -l -c ios在模拟器中运行我的项目时,我POST/members/login(身份验证过滤器)的请求失败并出现以下错误,而对(控制器端点)的POST请求成功:/members/signup

{"headers":{"normalizedNames":{},"lazyUpdate":null,"headers":{}},"status":0,"statusText":"Unknown Error","url":null,"ok":false,"name":"HttpErrorResponse","message":"Http failure response for (unknown url): 0 Unknown Error","error":{"isTrusted":true}}

来自 Web Inspector 的错误如下:

[Error] Origin http://172.20.10.2:8100 is not allowed by Access-Control-Allow-Origin.
[Error] XMLHttpRequest cannot load http://172.20.10.2:8080/member/login due to access control checks.
[Error] Failed to load resource: Origin http://172.20.10.2:8100 is not allowed by Access-Control-Allow-Origin. (login, line 0)

请求响应的标头OPTIONS如下:

Allow →POST
X-Content-Type-Options →nosniff
X-XSS-Protection →1; mode=block
Cache-Control →no-cache, no-store, max-age=0, must-revalidate
Pragma →no-cache
Expires →0
X-Frame-Options →DENY
Content-Length →0
Date →Fri, 05 Apr 2019 11:53:58 GMT

请求响应的标头POST是:

X-Content-Type-Options →nosniff
X-XSS-Protection →1; mode=block
Cache-Control →no-cache, no-store, max-age=0, must-revalidate
Pragma →no-cache
Expires →0
X-Frame-Options →DENY
Access-Control-Expose-Headers →*
Access-Control-Allow-Origin →*
x-auth-token →b5f39afe-ad54-40b1-a690-0c79f800abd6
Content-Length →0
Date →Fri, 05 Apr 2019 12:08:30 GMT

这与请求的标头相同/member/signup

表明--livereload仍然会启动一个带有来源请求的 Web 服务器,因此可能会遇到 CORS 问题,但是当我在没有它的情况下运行时(实际上是打包应用程序并在我的组织内分发)我的请求仍然失败(使用ionic cordova build ios和来自 XCode 项目)。

所以我的问题是:

  1. 为什么即使我打包应用程序并在没有 livereload 的情况下分发我的请求也会失败(我的请求的来源不应该是空的吗?)
  2. 如何为我的身份验证过滤器启用 CORS?

参考:

  1. 这里引用了离子代理。我不能在生产中使用代理。我想知道如何启用 CORS,实际上,为什么它首先发生在设备上没有来源的情况下。

  2. 没有帮助,我遇到了同样的问题。

  3. 这个也无济于事。

标签: cordovaspring-bootionic-frameworkcorsionic3

解决方案


推荐阅读