跨域問題(普通跨域和springsecurity跨域)

浮白呀發表於2024-10-01

跨域問題老生常談了, 前後端分離專案會用到,瀏覽器端的請求需要ip,協議,埠完全一直否則瀏覽器會攔截

普通:

package com.example.openai.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 CorsConfig implements WebMvcConfigurer {
 @Override
 public void addCorsMappings(CorsRegistry registry) {
           // 設定允許跨域的路徑
  registry.addMapping("/**")
          // 設定允許跨域請求的域名
          .allowedOriginPatterns("*")
          // 是否允許cookie
          .allowCredentials(true)
          // 設定允許的請求方式
          .allowedMethods("GET", "POST", "DELETE", "PUT")
          // 設定允許的header屬性
          .allowedHeaders("*")
          // 跨域允許時間
          .maxAge(3600);
 }
 }

springsecurity

@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private  JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter;
    @Autowired
    private AccessDeniedExceptionImpl accessDeniedException;
    @Autowired
    private Renzheng renzheng;
    @Bean
    public BCryptPasswordEncoder passwordEncoder(){
        return new  BCryptPasswordEncoder();
    }
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                //關閉csrf
                .csrf().disable()
                //不透過Session獲取SecurityContext

                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .authorizeRequests()
                // 對於登入介面 允許匿名訪問
                .antMatchers("/user/login").anonymous()
                // 除上面外的所有請求全部需要鑑權認證
                .anyRequest().authenticated();
        http.addFilterBefore(jwtAuthenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);
        http.exceptionHandling()
                //認證處理
                .authenticationEntryPoint(renzheng)
                //異常處理
                .accessDeniedHandler(accessDeniedException);
        http.cors();
    }

設定http.cors()即可

相關文章