在poster中,当我用Authorization和token值输入我的post请求时,它就工作了,但当我想用axios检查它时,它会给我403 Http错误(我已经在axios中提供了授权头(。(我在Bearer上的令牌是localStorage.getItem("CurrentUser"(}(我把我的axios放在下面(当我检查令牌和请求字符串时,它们与poster完全相同(:
try {
await axios.post("http://localhost:8080/admins/post/" + allemployees[index].id,
{ headers: {'Authorization': localStorage.getItem("CurrentUser")} });
}
我还放了我的security.config,也许问题就在那里:
@Configuration
@EnableWebSecurity
public class SecurityConfig{
private JwtAuthenticationEntryPoint handler;
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Bean
public AuthTokenFilter jwtAuthenticationFilter() {
return new AuthTokenFilter();
}
@Bean
public AuthenticationManager authenticationManager(AuthenticationConfiguration authenticationConfiguration) throws Exception {
return authenticationConfiguration.getAuthenticationManager();
}
@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true);
config.setAllowedOrigins(List.of("http://localhost:3000"));
config.addAllowedHeader("*");
config.addAllowedMethod("*");
source.registerCorsConfiguration("/**", config);
return new CorsFilter(source);
}
@Bean
public SecurityFilterChain configure(HttpSecurity httpSecurity) throws Exception {
httpSecurity
.cors()
.and()
.csrf().disable()
.exceptionHandling().authenticationEntryPoint(handler).and()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
.authorizeRequests()
.antMatchers("/api/**")
.permitAll()
.anyRequest().authenticated()
.and()
.logout()
.logoutRequestMatcher(new AntPathRequestMatcher("/logout", "POST"))
.logoutSuccessUrl("http://localhost:3000/")
.invalidateHttpSession(true);
httpSecurity.addFilterBefore(jwtAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);
return httpSecurity.build();
}
}
我该如何解决这个问题?非常感谢。
因为Postman
不强制执行CORS
,所以这就是它工作的原因。要启用CORS
,请在此处进行检查;
https://enable-cors.org/server.html