http://localhost:8081/free_bird/details/update/1 403 (Forbidden)

我用本机做后端,本机做前端,当我用前端访问进行update时出现如标题的异常

package com.example.free_bird.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
@EnableWebSecurity
public class SecurityConfig {
    private static final Logger logger = LoggerFactory.getLogger(SecurityConfig.class);

    public SecurityConfig() {
        logger.info("SecurityConfig initialized");
    }

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
                .authorizeHttpRequests((authorize) ->
                        authorize
                                // 允许所有请求访问
                                .anyRequest().permitAll()
                )
                .formLogin((form) ->
                        form
                                .loginPage("/free_bird/login")
                )
                .logout((logout) ->
                        logout
                                .logoutSuccessUrl("/free_bird/login")
                );
        http.cors(AbstractHttpConfigurer::disable);
        return http.build();
    }
}
package com.example.free_bird.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOriginPatterns("*")
                .allowedMethods("*")
                .allowedHeaders("*")
                .allowCredentials(true);
    }

}

请大侠指教,不胜感激!!

看看具体日志,403 (Forbidden) 是哪个环节导致的异常。

如果怀疑是跨域问题,你可以把你 WebConfig 配置类中的 addCorsMappings 配置方法删除掉。

然后,添加下面这个通用的跨域配置类:

import java.time.Duration;
import java.util.Arrays;
import java.util.stream.Stream;

import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.util.StringUtils;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.filter.CorsFilter;

/**
 * 
 * 全局跨域配置
 * 
 */
@Configuration
public class CorsFilterConfiguration {

    @Bean
    public FilterRegistrationBean<CorsFilter> corsFilter() {
        CorsFilter corsFilter = new CorsFilter(request -> {

            String origin = request.getHeader(HttpHeaders.ORIGIN);

            if (!StringUtils.hasText(origin)) {
                // 非跨域请求
                return null;
            }

            CorsConfiguration config = new CorsConfiguration();
            // 允许所有域
            config.addAllowedOrigin(origin);

            // 允许所有请求 Header
            String requestHeders = request.getHeader(HttpHeaders.ACCESS_CONTROL_REQUEST_HEADERS);
            if (StringUtils.hasText(requestHeders)) {
                config.setAllowedHeaders(Stream.of(requestHeders.split(",")).map(String::trim).distinct().toList());
            }
            
            // 默认允许 Javascript 访问的响应头
            config.setExposedHeaders(Arrays.asList("Cache-Control", "Content-Language", "Content-Length", 
                    "Content-Type", "Expires", "Last-Modified", "Pragma"));
            
            // 允许携带凭证
            config.setAllowCredentials(true);
            
            // 允许所有请求方法
            config.setAllowedMethods(Arrays.asList("GET", "HEAD", "POST", "PUT", 
                    "PATCH", "DELETE", "OPTIONS", "TRACE"));
            
            // 预检缓存 30 分钟
            config.setMaxAge(Duration.ofMinutes(30));

            return config;
        });

        FilterRegistrationBean<CorsFilter> registrationBean = new FilterRegistrationBean<>(corsFilter);
        registrationBean.addUrlPatterns("/*"); // 拦截所有请求
        registrationBean.setOrder(Ordered.HIGHEST_PRECEDENCE); // 最先执行
        return registrationBean;
    }
}

更多的细节,你可以参阅下面的文章:

非常感谢您的指导,我把 WebConfig改成您指导的方法,但还是403错误, :joy:

你用到了security,那么security的过滤里面没有放行的话你要先认证的撒