Java 为什么JDBC身份验证在spring boot和react中使用CORS失败?

Java 为什么JDBC身份验证在spring boot和react中使用CORS失败?,java,spring,spring-boot,spring-security,Java,Spring,Spring Boot,Spring Security,我尝试在后端使用spring security使用JDBC身份验证登录,并在前端进行响应。我在spring安全配置中添加了CORS过滤器,但即使使用正确的用户名和密码,我也会得到错误的用户名密码。登录在jsp中运行良好。我使用.csrf().disable()禁用了csrf检查 这是如何记录post请求的网络日志的 这是我从服务器得到的响应 我添加了全局CORS配置,如下所示 AppConfig.java @Configuration @EnableWebMvc @ComponentScan

我尝试在后端使用spring security使用JDBC身份验证登录,并在前端进行响应。我在spring安全配置中添加了CORS过滤器,但即使使用正确的用户名和密码,我也会得到错误的用户名密码。登录在jsp中运行良好。我使用
.csrf().disable()
禁用了csrf检查

这是如何记录post请求的网络日志的

这是我从服务器得到的响应

我添加了全局CORS配置,如下所示

AppConfig.java

@Configuration
@EnableWebMvc
@ComponentScan(basePackages = { "net.kzn.onlineshopping.*", 
"net.kzn.shoppingbackend.*" })
public class AppConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
    registry.addMapping("/**")
    .allowedMethods("HEAD", "GET", "PUT", "POST", "DELETE", "PATCH");
}
}
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

@Autowired DataSource dataSource;

@Autowired
private BCryptPasswordEncoder bCryptPasswordEncoder;
 @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/resources/**");
    }

@Override
protected void configure(HttpSecurity http) throws Exception {
    http
    .cors()
        .and()
        .csrf().disable()   
        .authorizeRequests()                                                                
            .antMatchers("/**").permitAll()                  
            .antMatchers("/manage/**").hasRole("ADMIN")                                      
            .antMatchers("/cart/**").hasRole("USER")            
            .anyRequest().authenticated()                                                   
            .and()
        .formLogin()
            .loginPage("/login")
            .permitAll()
            .and()
            .logout()
            .permitAll()
            .and()
        .exceptionHandling()
            .accessDeniedPage("/access-denied")
        .and()
            .httpBasic();

}

@Bean
public CorsConfigurationSource corsConfigurationSource() {
    CorsConfiguration configuration = new CorsConfiguration();
    configuration.setAllowedOrigins(Arrays.asList("*"));
    configuration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"));
    configuration.setAllowCredentials(true);
    configuration.setAllowedHeaders(Arrays.asList("authorization", "Cache-Control", "content-type", "x-auth-token", "JDBC"));
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    source.registerCorsConfiguration("/**", configuration);
    return source;
}

@Override
public void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth
        .jdbcAuthentication()
        .usersByUsernameQuery("select email, password, enabled from user_detail where email = ?")
        .authoritiesByUsernameQuery("select email, role from user_detail where email = ?")
        .dataSource(dataSource)
        .passwordEncoder(bCryptPasswordEncoder);
     System.out.println("inside security config");
}

}
@RequestMapping(value = "/login")
public Map<String, Object> login(
        @RequestParam(name = "error", required = false) String error,
        @RequestParam(name = "logout", required = false) String logout) {
    Map<String, Object> login = new HashMap<String, Object>();
    System.out.println("Login..");
    login.put("title", "Login");
    if (error != null) { 
        login.put("message", "Username and Password is invalid!");
    }
    if (logout != null) {
        login.put("logout", "You have logged out successfully!");
    }
    return login; 
}
cors的过滤器配置如下 SecurityConfig.java

@Configuration
@EnableWebMvc
@ComponentScan(basePackages = { "net.kzn.onlineshopping.*", 
"net.kzn.shoppingbackend.*" })
public class AppConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
    registry.addMapping("/**")
    .allowedMethods("HEAD", "GET", "PUT", "POST", "DELETE", "PATCH");
}
}
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

@Autowired DataSource dataSource;

@Autowired
private BCryptPasswordEncoder bCryptPasswordEncoder;
 @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/resources/**");
    }

@Override
protected void configure(HttpSecurity http) throws Exception {
    http
    .cors()
        .and()
        .csrf().disable()   
        .authorizeRequests()                                                                
            .antMatchers("/**").permitAll()                  
            .antMatchers("/manage/**").hasRole("ADMIN")                                      
            .antMatchers("/cart/**").hasRole("USER")            
            .anyRequest().authenticated()                                                   
            .and()
        .formLogin()
            .loginPage("/login")
            .permitAll()
            .and()
            .logout()
            .permitAll()
            .and()
        .exceptionHandling()
            .accessDeniedPage("/access-denied")
        .and()
            .httpBasic();

}

@Bean
public CorsConfigurationSource corsConfigurationSource() {
    CorsConfiguration configuration = new CorsConfiguration();
    configuration.setAllowedOrigins(Arrays.asList("*"));
    configuration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"));
    configuration.setAllowCredentials(true);
    configuration.setAllowedHeaders(Arrays.asList("authorization", "Cache-Control", "content-type", "x-auth-token", "JDBC"));
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    source.registerCorsConfiguration("/**", configuration);
    return source;
}

@Override
public void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth
        .jdbcAuthentication()
        .usersByUsernameQuery("select email, password, enabled from user_detail where email = ?")
        .authoritiesByUsernameQuery("select email, role from user_detail where email = ?")
        .dataSource(dataSource)
        .passwordEncoder(bCryptPasswordEncoder);
     System.out.println("inside security config");
}

}
@RequestMapping(value = "/login")
public Map<String, Object> login(
        @RequestParam(name = "error", required = false) String error,
        @RequestParam(name = "logout", required = false) String logout) {
    Map<String, Object> login = new HashMap<String, Object>();
    System.out.println("Login..");
    login.put("title", "Login");
    if (error != null) { 
        login.put("message", "Username and Password is invalid!");
    }
    if (logout != null) {
        login.put("logout", "You have logged out successfully!");
    }
    return login; 
}
controller.java

@Configuration
@EnableWebMvc
@ComponentScan(basePackages = { "net.kzn.onlineshopping.*", 
"net.kzn.shoppingbackend.*" })
public class AppConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
    registry.addMapping("/**")
    .allowedMethods("HEAD", "GET", "PUT", "POST", "DELETE", "PATCH");
}
}
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

@Autowired DataSource dataSource;

@Autowired
private BCryptPasswordEncoder bCryptPasswordEncoder;
 @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/resources/**");
    }

@Override
protected void configure(HttpSecurity http) throws Exception {
    http
    .cors()
        .and()
        .csrf().disable()   
        .authorizeRequests()                                                                
            .antMatchers("/**").permitAll()                  
            .antMatchers("/manage/**").hasRole("ADMIN")                                      
            .antMatchers("/cart/**").hasRole("USER")            
            .anyRequest().authenticated()                                                   
            .and()
        .formLogin()
            .loginPage("/login")
            .permitAll()
            .and()
            .logout()
            .permitAll()
            .and()
        .exceptionHandling()
            .accessDeniedPage("/access-denied")
        .and()
            .httpBasic();

}

@Bean
public CorsConfigurationSource corsConfigurationSource() {
    CorsConfiguration configuration = new CorsConfiguration();
    configuration.setAllowedOrigins(Arrays.asList("*"));
    configuration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"));
    configuration.setAllowCredentials(true);
    configuration.setAllowedHeaders(Arrays.asList("authorization", "Cache-Control", "content-type", "x-auth-token", "JDBC"));
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    source.registerCorsConfiguration("/**", configuration);
    return source;
}

@Override
public void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth
        .jdbcAuthentication()
        .usersByUsernameQuery("select email, password, enabled from user_detail where email = ?")
        .authoritiesByUsernameQuery("select email, role from user_detail where email = ?")
        .dataSource(dataSource)
        .passwordEncoder(bCryptPasswordEncoder);
     System.out.println("inside security config");
}

}
@RequestMapping(value = "/login")
public Map<String, Object> login(
        @RequestParam(name = "error", required = false) String error,
        @RequestParam(name = "logout", required = false) String logout) {
    Map<String, Object> login = new HashMap<String, Object>();
    System.out.println("Login..");
    login.put("title", "Login");
    if (error != null) { 
        login.put("message", "Username and Password is invalid!");
    }
    if (logout != null) {
        login.put("logout", "You have logged out successfully!");
    }
    return login; 
}
@RequestMapping(value=“/login”)
公共地图登录(
@RequestParam(name=“error”,required=false)字符串错误,
@RequestParam(name=“logout”,required=false)字符串(logout){
Map login=newhashmap();
System.out.println(“登录…”);
登录。放置(“标题”、“登录”);
如果(错误!=null){
login.put(“消息”,“用户名和密码无效!”);
}
如果(注销!=null){
login.put(“注销”,“您已成功注销!”);
}
返回登录;
}

即使使用正确的用户名密码,为什么我会出错?我是否缺少任何配置?请帮助我。

在我的axios请求中添加应用程序/x-www-form-urlencoded后,我的问题解决了

export const addProjectTask = (username,password, history) => async dispatch => {

axios.post('http://localhost:8080/onlineshopping/login', 
   Qs.stringify({
    username: username,
    password: password
    }), {
    headers: { 
      "Content-Type": "application/x-www-form-urlencoded"
    }})
  .then(function (response) {
    console.log(response);
    history.push("/");  
  })
  .catch(function (error) {
    console.log(error);
  });

  };

问题中没有显示CORS错误。相反,屏幕截图中显示的响应详细信息似乎表明服务器CORS配置正在按预期工作。正如@dur所说,在添加应用程序/x-www-form-urlencodedi成功登录后,将内容类型更改为application/x-www-form-urlencoded。感谢您的帮助。请将代码、错误和数据添加为文本(),而不是图像。图片:A)不允许我们复制和粘贴代码/错误/数据进行测试;B) 不允许基于代码/错误/数据内容进行搜索;和。一般来说,文本格式的代码/错误/数据>>>>图像格式的代码/错误/数据>>无。如果图像添加了一些重要的信息,而这些信息并不仅仅是通过文本代码/错误/数据传达出来,则只能在代码格式的文本之外使用图像。@Makyen好的,我会记住这一点。