reactjs - 尝试从网站注销时 Spring Security 出错
问题描述
您好我正在构建一个网络应用程序,我刚刚实现了登录和注册的功能,现在问题是注销..
我有一个调用此函数注销的按钮:
const logoutUser = () => {
axios({
url: API.logout,
method: "POST",
withCredentials: true,
headers: {
"X-CSRF-TOKEN": _csrf.token,
},
});
};
这是我的 Spring Security 配置:
@Override
protected void configure(HttpSecurity http) throws Exception{
http
.authorizeRequests()
.antMatchers("/api/getalltopics").permitAll()
.antMatchers("/api/findtopicbycodename/**").permitAll()
.antMatchers(HttpMethod.POST,"/api/createtopic").hasRole("ADMIN")
.antMatchers("/me").permitAll()
.antMatchers("/login", "/registeruser").permitAll()
.antMatchers("/dologoutuser").permitAll()
.antMatchers("/getcsrftoken").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.defaultSuccessUrl("http://192.168.1.105:3000/", true)
.and()
.logout()
.logoutUrl("/dologoutuser")
.deleteCookies("JSESSIONID");
http.cors(withDefaults());
}
@Bean
CorsConfigurationSource corsConfigurationSource(){
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.setAllowedOrigins(Arrays.asList("http://192.168.1.105:3000"));
corsConfiguration.setAllowedMethods(Arrays.asList("POST"));
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/dologoutuser", corsConfiguration);
return source;
}
(是的,我知道您可以将多个链接放入单个 .antMatchers,此代码目前正在处理中)
现在,当我点击注销按钮时,我的控制台中出现 3 个错误:
1.OPTIONS http://192.168.1.105:8080/login?logout 403
2.Access to XMLHttpRequest at 'http://192.168.1.105:8080/login?logout' (redirected from 'http://192.168.1.105:3000/dologoutuser') from origin 'http://192.168.1.105:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
3.Uncaught (in promise) Error: Network Error
at createError (createError.js:16)
at XMLHttpRequest.handleError (xhr.js:81)
此外,如果我在单击注销按钮后用 F5 刷新页面,它实际上会注销我,但显然我在这里做错了。谢谢你的帮助
解决方案
您将 cors 允许的来源配置错误。您应该添加 192.168.1.105 (或托管您的 reactjs 应用程序的主机)作为允许的来源,而不是 /dologoutuser