JAVA跨域配置(实用)

实用跨域配置

package com.iptv.jySysMgrPlatform.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Configuration
public class CorsConfigTwo {

    private CorsConfiguration buildConfig(){
        List<String> ipAddrs=new ArrayList<>();
        ipAddrs.add("127.0.0.1");
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.setAllowedOrigins(ipAddrs);
        corsConfiguration.addAllowedHeader("*");
        corsConfiguration.addAllowedMethod("*");
        corsConfiguration.setAllowCredentials(true);
        return corsConfiguration;
    }

    @Bean
    public CorsFilter corsFilter(){
        UrlBasedCorsConfigurationSource urlBasedCorsConfigurationSource = new UrlBasedCorsConfigurationSource();
        urlBasedCorsConfigurationSource.registerCorsConfiguration("/**",buildConfig());
        return new CorsFilter(urlBasedCorsConfigurationSource);
    }

}

添加跨域配置使用该配置可实现效果,自定义ip允许跨域防止ip访问漏洞的发生

你可能感兴趣的:(跨域,java,安全,spring)