java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > Java后端配置允许跨域

Java后端配置允许跨域方式

作者:白天睡晚上卷

本文介绍了在不同技术和框架中配置跨域资源共享(CORS)的方法,包括使用SpringMVC的@CrossOrigin注解、SpringBoot的全局CORS配置、SpringSecurity中的CORS集成以及手动设置响应头,根据具体需求和技术栈,选择合适的方法来确保跨域请求的安全性和有效性

1. 使用 @CrossOrigin 注解 (Spring MVC)

如果你使用的是Spring MVC或Spring Boot,最简单的方法是直接在控制器类或方法上使用@CrossOrigin注解来允许特定来源的跨域请求。

import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@CrossOrigin(origins = "http://example.com") // 允许来自example.com的跨域请求
public class MyController {

    @GetMapping("/api/data")
    public String getData() {
        return "Data from server";
    }
}

你可以指定多个来源,或者使用*来允许所有来源(但不推荐用于生产环境):

@CrossOrigin(origins = "*") // 允许所有来源

2. 配置全局 CORS 支持 (Spring Boot)

为了在整个应用程序中统一配置CORS规则,而不是逐个控制器或方法进行配置,可以通过实现WebMvcConfigurer接口并在其中定义全局的CORS配置。

import org.springframework.context.annotation.Bean;
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 {

    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurer() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/**") // 应用于所有路径
                    .allowedOrigins("http://example.com") // 允许的来源
                    .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS") // 允许的方法
                    .allowCredentials(true) // 是否允许发送凭证信息(如Cookies)
                    .maxAge(3600); // 预检请求的有效期(秒)
            }
        };
    }
}

3. 使用 Spring Security 配置 CORS (如果使用了 Spring Security)

如果你的应用程序使用了Spring Security,你还需要确保在安全配置中也启用了CORS支持。

import org.springframework.context.annotation.Bean;
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.configuration.WebSecurityConfigurerAdapter;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors().and()
            .csrf().disable(); // 根据需要启用或禁用CSRF保护
    }

    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(true);
        config.addAllowedOrigin("http://example.com");
        config.addAllowedHeader("*");
        config.addAllowedMethod("*");
        source.registerCorsConfiguration("/**", config);
        return new CorsFilter(source);
    }
}

4. 手动设置响应头 (Servlet API)

对于不使用Spring框架的项目,可以在Servlet中手动设置响应头来允许跨域请求。

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class MyServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        
        // 设置CORS响应头
        response.setHeader("Access-Control-Allow-Origin", "http://example.com");
        response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization");

        // 处理预检请求
        if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
            response.setStatus(HttpServletResponse.SC_OK);
        } else {
            // 正常处理请求
            response.getWriter().print("Data from server");
        }
    }
}

总结

根据你的技术栈和需求选择最适合的方式来配置CORS。

无论是通过注解、全局配置还是手动设置响应头,关键是确保你正确地指定了允许的来源、方法和其他必要的参数。

如果你使用的是Spring框架,特别是Spring Boot,推荐使用@CrossOrigin注解或全局配置的方式,因为它们更简洁且易于维护。

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

您可能感兴趣的文章:
阅读全文