原因:缺少CORS头’Access-Control-Allow-Origin’ / Spring Boot

huangapple go评论93阅读模式
英文:

Reason: CORS header ‘Access-Control-Allow-Origin’ missing / Spring Boot

问题

我有一个基本的Spring Boot REST应用程序和Angular应用程序。(使用JWT)

但是,由于以下错误,我无法进行任何请求:(即使我在响应头中添加了 "Access-Control-Allow-Origin", "*"

跨源请求被阻止:同源策略不允许读取位于 http://localhost:8080/api/login 的远程资源。(原因:缺少CORS头 'Access-Control-Allow-Origin')。

跨源请求被阻止:同源策略不允许读取位于 http://localhost:8080/api/login 的远程资源。(原因:CORS请求未成功)。

以下是安全配置:

public class AuthTokenFilter extends OncePerRequestFilter {
// ...
}

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(
        // securedEnabled = true,
        // jsr250Enabled = true,
        prePostEnabled = true)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .cors().and().csrf().disable()
                .authorizeRequests()
                .antMatchers(WebUrls.API.API + WebUrls.LOGIN.LOGIN,
                        WebUrls.API.API + WebUrls.LOGIN.REGISTER,
                        WebUrls.API.API + WebUrls.LOGIN.REFRESH_TOKEN)
                .permitAll()
                .anyRequest().authenticated();
        http.addFilterBefore(authJwtTokenFilter(), UsernamePasswordAuthenticationFilter.class);
        http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
    }
}

以下是我添加CORS头的地方:

@Component
public class MyCorsFilter implements Filter {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "GET, PUT, POST, DELETE, OPTIONS");
        response.setHeader("Access-Control-Allow-Headers", "*");
        filterChain.doFilter(servletRequest, servletResponse);
    }
}
英文:

I have a basic spring boot rest application and angular application. (Using JWT)

However, I can not make any request because of this error:(even I add "Access-Control-Allow-Origin", "*" to response header

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:8080/api/login. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:8080/api/login. (Reason: CORS request did not succeed).

Here is the security configuration:

public class AuthTokenFilter extends OncePerRequestFilter {
// ...
}

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(
        // securedEnabled = true,
        // jsr250Enabled = true,
        prePostEnabled = true)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .cors().and().csrf().disable()
                .authorizeRequests()
                .antMatchers(WebUrls.API.API + WebUrls.LOGIN.LOGIN,
                        WebUrls.API.API + WebUrls.LOGIN.REGISTER,
                        WebUrls.API.API + WebUrls.LOGIN.REFRESH_TOKEN)
                .permitAll()
                .anyRequest().authenticated();
        http.addFilterBefore(authJwtTokenFilter(), UsernamePasswordAuthenticationFilter.class);
        http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
    }
}

Here is the place where I am adding cors headers:

@Component
public class MyCorsFilter implements Filter {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "GET, PUT, POST, DELETE, OPTIONS");
        response.setHeader("Access-Control-Allow-Headers", "*");
        filterChain.doFilter(servletRequest, servletResponse);
    }
}

答案1

得分: 2

请尝试以下配置使其正常工作。这将允许来自任何源的CORS请求访问应用程序中的任何端点。

@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {
 
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**");
    }
}
英文:

Please try the below configuration to make this work. This enables CORS requests from any origin to any endpoint in the application.

@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {
 
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**");
    }
}

huangapple
  • 本文由 发表于 2020年10月11日 08:47:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/64299652.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定