我正在尝试使用 JDBC 身份验证在后端使用 spring security 进行登录并在前端使用react。我在 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");
}
}
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/