java - 为什么 JDBC 身份验证在 Spring Boot 和 React 中因 CORS 失败?

标签 java spring spring-boot spring-security

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

这就是post请求的网络日志

enter image description here

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

enter image description here

我添加了全局 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");
}
}

cors的过滤器配置如下 SecurityConfig.java

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

}

controller.java

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

即使使用正确的用户名密码,为什么我会收到错误消息?我这里缺少任何配置吗?请帮助我。

最佳答案

在我的 axios 请求中添加 application/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);
  });

  };

关于java - 为什么 JDBC 身份验证在 Spring Boot 和 React 中因 CORS 失败?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54250354/

相关文章:

java - 使用 Spring @Transactionnal,Spring 如何知道使用哪个数据源?

java - 如何使用带有 Spring Security 5.1+ 的谷歌 OIDC 对用户进行身份验证

java - 数据源无法通过 Spring boot 应用程序初始化?

java - 使用二进制编码将 byte[] 转换为 String

java - 找不到标志。正在寻找父类(super class)而不是子类

java - JSF 2.0。无法在 preRenderView 事件处理程序中获取 POST 参数和 cookie

java - 无法实例化 [org.thymeleaf.templateresolver.ServletContextTemplateResolver] : No default constructor found

java - 设置图标时遇到问题

java - Spring:HSQL-无法执行数据库脚本

java - StringRedisTemplate 上的 Spring Data Redis : java. lang.NullPointerException