springboot filter 多域名跨域访问

本文介绍了一个用于判断用户是否登录的过滤器设计,该过滤器通过设定允许路径来避免对特定URL的拦截,同时实现了跨域请求的处理,确保了系统的安全性与易用性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package com.wolfking.jeesite.common.filter;

/**
 * @Auther: 宋甲贺
 * @Date: 2018/12/21
 * @Description: com.wolfking.jeesite.common.filter
 * @version: 1.0
 */

//判断是否登陆的 filter

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URI;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

// /* 表示全部拦截
//@WebFilter(filterName = "loginFilter",urlPatterns = "/*")
public class LoginFilter implements Filter {
    //这里面 填写不需要 被拦截的地址
    private static final Set<String> ALLOWED_PATHS = Collections.unmodifiableSet(
            new HashSet<String>( Arrays.asList("/login","/isLogin","/findCategory") )
    );

    //初始化调用的方法
    //当服务器 被启动的时候,调用
    public void init(FilterConfig filterConfig) throws ServletException { }
    private static URI getIP(URI uri) {
        URI effectiveURI = null;

        try {
            // URI(String scheme, String userInfo, String host, int port, String
            // path, String query,String fragment)
            effectiveURI = new URI(uri.getScheme(), uri.getUserInfo(), uri.getHost(), uri.getPort(), null, null, null);
        } catch (Throwable var4) {
            effectiveURI = null;
        }

        return effectiveURI;
    }

    // 跨域域名设置
    public static final String[] ALLOW_DOMAIN = { "http://localhost",
            "http://192.168.0.100" };
    //拦截的方法
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain filterChain) throws IOException, ServletException {


        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;
        String url2=request.getScheme()+"://"+ request.getServerName();
        System.out.println(url2);
        if (Arrays.asList(ALLOW_DOMAIN).contains(url2)) {
            //解决跨域的问题
            response.setHeader("Access-Control-Allow-Origin", "*");
            response.setHeader("Access-Control-Allow-Credentials", "true");
            response.setHeader("Access-Control-Allow-Headers", "Content-Type,Content-Length, Authorization, Accept,X-Requested-With,X-App-Id, X-Token");
            response.setHeader("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
            response.setHeader("Access-Control-Max-Age", "3600");


            String path = request.getRequestURI().substring(request.getContextPath().length()).replaceAll("[/]+$", "");
            boolean allowePath = ALLOWED_PATHS.contains(path);

       /* if (!allowePath) {  //需要拦截的方法
            Object aa = request.getSession().getAttribute("user");
            if (aa != null) {
                filterChain.doFilter(request,response);
            }
            else {
                response.getWriter().write("noLogin");
            }
        } else {  //不需要被拦截的方法*/
            //直接放行
            filterChain.doFilter(request, response);
            /*}*/
        }else{
            response.getWriter().write("noLogin");
        }


    }

    //销毁时候调用的方法
    public void destroy() { }
}

<think>我们正在配置Spring Boot应用以支持CORS(资源共享)。CORS是一种机制,允许Web应用服务器进行访问控制,从而使数据传输得以安全进行。 在Spring Boot中,我们可以通过多种方式配置CORS,例如: 1. 使用注解`@CrossOrigin`在控制器(Controller)或方法上。 2. 通过全局配置(定义一个`WebMvcConfigurer` bean)来设置全局CORS规则。 根据用户需求,他可能希望有一个全局配置,这样就不需要在每个控制器上添加注解。 我们将使用全局配置的方式,因为这样更集中且易于管理。 步骤: 1. 创建一个配置类,实现`WebMvcConfigurer`接口,并重写`addCorsMappings`方法。 2. 在方法中,我们可以通过`CorsRegistry`对象来添加CORS映射和配置。 例如,我们可以允许所有来源(origins)、所有请求头(headers)和所有方法(methods),但实际应用中应根据需要限制。 注意:在Spring Boot 2.4及以上版本,可能需要考虑新的配置方式(因为Spring Framework 5.3之后有一些变化),但基本方式仍然适用。 另外,我们也可以使用`application.properties`或`application.yml`文件来配置一些CORS属性,但这种方式不如Java配置灵活,通常只适用于简单场景。因此,我们推荐使用Java配置。 根据引用[3]的内容,我们知道Spring Boot的配置文件可以设置一些服务器相关的属性,但CORS配置通常不在该文件中直接设置。 因此,我们采用Java配置的方式。 示例代码: 创建一个名为`WebConfig`的配置类,内容如下: ```java 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("/**") // 允许所有路径 .allowedOrigins("*") // 允许所有来源 .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS") // 允许的HTTP方法 .allowedHeaders("*") // 允许所有请求头 .allowCredentials(false) // 不允许发送凭证(如cookies),因为允许了所有来源,所以这里设为false。如果需要凭证,应指定具体来源,并设为true .maxAge(3600); // 预检请求的有效期,单位秒 } } ``` 注意: - `allowedOrigins("*")`表示允许所有来源,但在生产环境中,建议指定具体的来源(如"http://example.com")以提高安全性。 - `allowCredentials(true)`和`allowedOrigins("*")`不能同时使用,因为这样会存在安全风险。如果需要凭证,必须指定具体的来源(例如`allowedOrigins("http://trusted-domain.com")`)并将`allowCredentials`设置为`true`。 - 上述配置中,我们禁用了凭证(`allowCredentials(false)`),并允许了所有来源,所以是安全的。 另外,如果使用Spring Security,还需要确保Spring Security不会覆盖CORS配置。通常,Spring Security有一个专门的CORS配置,但如果我们使用上述方式配置了全局CORS,并且没有在Spring Security中覆盖,那么应该可以工作。如果同时使用Spring Security,可能需要额外配置。 如果用户使用了Spring Security,那么可能需要结合Spring Security的CORS配置。但根据问题,用户没有提到Spring Security,所以我们先提供基本配置。 因此,我们只需要添加上述配置类即可。 另外,我们也可以使用过滤器(Filter)的方式配置CORS,但Spring MVC提供了更高级的抽象,所以推荐使用`WebMvcConfigurer`。 相关问题: 1. 如何为特定的URL模式配置CORS? 2. 在Spring Boot中配置CORS时,如何处理预检请求(preflight request)? 3. 如果同时使用Spring Security,如何配置CORS?</think>### 在 Spring Boot 中启用 CORS 配置 在 Spring Boot 应用中配置 CORS(资源共享)主要有以下三种方式,根据需求选择全局配置或局部配置: --- #### 方法 1:全局配置(推荐) 在配置类中实现 `WebMvcConfigurer` 接口,覆盖 `addCorsMappings()` 方法: ```java 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("/**") // 匹配所有路径 .allowedOrigins("*") // 允许所有源(生产环境应指定具体域名) .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS") // 允许的HTTP方法 .allowedHeaders("*") // 允许所有请求头 .allowCredentials(false) // 是否允许凭据(cookies) .maxAge(3600); // 预检请求缓存时间(秒) } } ``` --- #### 方法 2:使用 `@CrossOrigin` 注解(局部配置) 在单个控制器或方法上添加注解: ```java @RestController @CrossOrigin(origins = "https://your-domain.com") // 允许特定源 public class ApiController { @GetMapping("/data") @CrossOrigin(maxAge = 1800) // 可覆盖类级别配置 public ResponseEntity<?> getData() { return ResponseEntity.ok("CORS enabled"); } } ``` --- #### 方法 3:通过 `application.properties` 配置(部分属性) 部分基础属性可在配置文件中设置[^2][^3]: ```properties # 允许的源(多个用逗号分隔) endpoints.cors.allowed-origins=http://localhost:3000,https://example.com # 允许的方法 endpoints.cors.allowed-methods=GET,POST # 预检请求缓存时间 endpoints.cors.max-age=1800 ``` --- #### 关键配置说明: 1. **`allowedOrigins`** - 设为 `*` 允许所有(不能与 `allowCredentials=true` 同时使用) - 生产环境建议指定具体域名:`.allowedOrigins("https://your-frontend.com")` 2. **`allowCredentials`** - 若需传递 cookies/JWT 令牌,设为 `true` 并明确指定域名(不能为 `*`) 3. **预检请求处理** - Spring Boot 自动处理 `OPTIONS` 请求,无需额外代码 - 通过 `maxAge` 减少浏览器预检请求频率 > ⚠️ 安全提示:避免全局配置中使用 `.allowedOrigins("*").allowCredentials(true)` 组合,这会引发安全风险[^1]。 --- #### 验证配置是否生效 使用 `curl` 测试预检请求: ```bash curl -X OPTIONS http://your-springboot-server:8080/api/data \ -H "Origin: http://your-frontend.com" \ -H "Access-Control-Request-Method: POST" ``` 检查响应头是否包含: ```http Access-Control-Allow-Origin: http://your-frontend.com Access-Control-Allow-Methods: POST Access-Control-Max-Age: 3600 ``` --- ### 相关问题 1. 如何为 Spring Security 项目单独配置 CORS? 2. 当 CORS 配置不生效时,常见的排查步骤有哪些? 3. 在微服务架构中,CORS 应该配置在网关层还是服务层? 4. 为什么浏览器会发送 OPTIONS 预检请求?如何优化其性能? [^1]: Spring Boot 官方文档:https://docs.spring.io/spring-boot/docs/current/reference/html/web.html#web.cors [^2]: `application.properties` 配置项参考 [^3]: 内嵌容器端口配置说明
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值