HTTP 403错误在axios中,但在postman上工作

wnavrhmk  于 2022-11-07  发布在  Postman
关注(0)|答案(1)|浏览(316)

在postman中,当我输入我的post请求与授权和令牌值,然后它的工作,然而,当我想检查它与axios它给我403 Http错误(我已经在axios中提供了授权头).(我的令牌与载体是localStorage.getItem(“CurrentUser”)})我把我的axios下面(当我检查令牌和请求字符串,他们都完全相同的postman):

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();
}

}
我该怎么解决这个问题呢?谢谢。

ruarlubt

ruarlubt1#

因为Postman不强制CORS,所以这就是它工作的原因。要启用CORS,请在这里检查;
https://enable-cors.org/server.html

相关问题