I get the CORS error while testing my api, I already set the crossorigin configuration but it's not working, Java Spring, Authentication JWT

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

I get the CORS error while testing my api, I already set the crossorigin configuration but it's not working, Java Spring, Authentication JWT

问题

I created a web application with java spring, I'm using JWT as authentication mechanism, I always get the cors problem even after adding the configuration to allow cross origins, how could I fix it?
我创建了一个Java Spring的Web应用程序,我正在使用JWT作为身份验证机制,即使在添加允许跨域配置后,我仍然遇到跨域问题,如何修复它?

I'm using spring 6, and spring boot 3
我正在使用Spring 6和Spring Boot 3

I will provide some of the code, the informations provided are not enough, you could see the whole code on my github repo:
我将提供一些代码,提供的信息不足,您可以在我的GitHub仓库上查看完整的代码:
Github

The problem only happens when I call endpoints that requires authentication,
问题仅在我调用需要身份验证的端点时发生,

I think there is a problem with the request or the response sent by the server, or maybe the header of the request,
我认为请求或服务器发送的响应存在问题,或者可能是请求的标头,

it would be better if any of you have the solution to provide me an example of the request I should send using "axios or fetch"
如果你们中有人有解决方案,最好能为我提供使用"axios或fetch"发送的请求示例

Here is my authentication filter :
这是我的身份验证过滤器:

public class securityConfigurationFilter {

    private final jwtAuthenticationFIlter jwtAuthFilter;
    private final AuthenticationProvider authenticationProvider;
    private final LogoutHandler logoutHandler;

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity httpSecurity)throws Exception{

        httpSecurity
                .csrf()
                .disable()
                .authorizeHttpRequests()
                .requestMatchers(
                        "/api/v1/account/register",
                        "/api/v1/account/password-recovery/*/*",
                        "/api/v1/account/authenticate",
                        "/api/v1/account/emailValidation/*",
                        "/api/v1/questions",
                        "/swagger-ui/index.html#",
                        "/v2/api-docs",
                        "/v3/api-docs",
                        "/v3/api-docs/**",
                        "/swagger-ressources",
                        "/swagger-ressources/**",
                        "/configuration/ui",
                        "/configuration/security",
                        "/swagger-ui/**",
                        "/webjars/**",
                        "/swagger-ui.html"
                )
                .permitAll()
                .anyRequest()
                .authenticated()
                .and()
                .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .authenticationProvider(authenticationProvider)
                .addFilterBefore(jwtAuthFilter, UsernamePasswordAuthenticationFilter.class)
                .logout()
                .logoutUrl("/api/v1/account/logout")
                .addLogoutHandler(logoutHandler)
                .logoutSuccessHandler(
                        (request,
                         response,
                         authentication) ->
                        SecurityContextHolder.clearContext());
  return httpSecurity.build();
    }

And here is the webConfiguration :

@Configuration
public class webConfigCors implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry coreRegistry) {
        coreRegistry.addMapping("/**")
                .allowedOrigins("*")
                .allowedHeaders("*")
                .allowedMethods("*");
    }
}

I tried to add the crossorigin annotation for each endpoint,
我尝试为每个端点添加crossorigin注解,

I also tried to change the webcross configuration to accept credentials like this :
我还尝试更改webcross配置以接受凭据,如下所示:

@Bean
    public CorsWebFilter corsWebFilter() {
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowedOrigins(Arrays.asList("http://127.0.0.1:5500"));
        config.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE", "OPTIONS"));
        config.setAllowedHeaders(Arrays.asList("*"));
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", config);
        return new CorsWebFilter(source);
    }

And by the way I want it to be accessible by all the origins not only my local host as fixed in the configuration above
顺便说一下,我希望它可以被所有来源访问,而不仅仅是我的本地主机,就像上面的配置一样。

英文:

I created a web application with java spring, I'm using JWT as authentication mechanism, I always get the cors problem even after adding the configuration to allow cross origins, how could I fix it?
I'm using spring 6, and spring boot 3
I will provide some of the code, the informations provided are not enough, you could see the whole code on my github repo:
Github
The problem only happens when I call endpoints that requires authentication,
I think there is a problem with the request or the response sent by the server, or maybe the header of the request,
it would be better if any of you have the solution to provide me an example of the request I should send using "axios or fetch"
Here is my authentication filter :

public class securityConfigurationFilter {
private final jwtAuthenticationFIlter jwtAuthFilter;
private final AuthenticationProvider authenticationProvider;
private final LogoutHandler logoutHandler;
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity httpSecurity)throws Exception{
httpSecurity
.csrf()
.disable()
.authorizeHttpRequests()
.requestMatchers(
"/api/v1/account/register",
"/api/v1/account/password-recovery/*/*",
"/api/v1/account/authenticate",
"/api/v1/account/emailValidation/*",
"/api/v1/questions",
"/swagger-ui/index.html#",
"/v2/api-docs",
"/v3/api-docs",
"/v3/api-docs/**",
"/swagger-ressources",
"/swagger-ressources/**",
"/configuration/ui",
"/configuration/security",
"/swagger-ui/**",
"/webjars/**",
"/swagger-ui.html"
)
.permitAll()
.anyRequest()
.authenticated()
.and()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authenticationProvider(authenticationProvider)
.addFilterBefore(jwtAuthFilter, UsernamePasswordAuthenticationFilter.class)
.logout()
.logoutUrl("/api/v1/account/logout")
.addLogoutHandler(logoutHandler)
.logoutSuccessHandler(
(request,
response,
authentication) ->
SecurityContextHolder.clearContext());
return httpSecurity.build();
}

And here is the webConfiguration :

@Configuration
public class webConfigCors implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry coreRegistry) {
coreRegistry.addMapping("/**")
.allowedOrigins("*")
.allowedHeaders("*")
.allowedMethods("*");
}
}

I tried to add the crossorigin annotation for each endpoint,
I also tried to change the webcross configuration to accept credentiels like this :

@Bean
public CorsWebFilter corsWebFilter() {
CorsConfiguration config = new CorsConfiguration();
config.setAllowedOrigins(Arrays.asList("http://127.0.0.1:5500"));
config.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE", "OPTIONS"));
config.setAllowedHeaders(Arrays.asList("*"));
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", config);
return new CorsWebFilter(source);
}

,
And by the way I want it to be accessible by all the origins not only my local host as fixed in the configuration above

答案1

得分: 0

我认为我找到了解决方案,如果您在securityFilter bean的相同配置中遇到相同的问题,您应该在配置中的.disable()之后立即添加以下行,您将会得到如下所示的内容:

@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity httpSecurity) throws Exception {
    httpSecurity
        .csrf()
        .disable()
        .cors()  // 这是如何禁用跨域
        .authorizeHttpRequests()
.... 配置的其余部分
英文:

I think I found the solution, if you have the same problem with the same configuration in securityFilter bean, you should add the following line right after .disable() in the configuration, you will have something like this :

 @Bean
public SecurityFilterChain securityFilterChain(HttpSecurity httpSecurity)throws Exception{
httpSecurity
.csrf()
.disable()
.cors()  // this is how to disable cors 
.authorizeHttpRequests()

.... the rest of the configuration

huangapple
  • 本文由 发表于 2023年6月5日 05:49:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/76402537.html
匿名

发表评论

匿名网友

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

确定