package com.vilicode.filter; import com.vilicode.bean.User; import javax.servlet.*; import javax.servlet.annotation.WebFilter; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; @WebFilter(filterName = "AdminFilter",urlPatterns = "/admin/*") public class AdminFilter implements Filter { public void destroy() { } public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException { HttpServletRequest request = (HttpServletRequest)req; HttpServletResponse requestp = (HttpServletResponse)resp; User u = (User) request.getSession().getAttribute("user"); if(u==null || u.isAdmin()==false) { requestp.sendRedirect("../index.action"); }else { // pass the request along the filter chain chain.doFilter(req, resp); } } public void init(FilterConfig config) throws ServletException { } }
时间: 2024-04-28 17:25:44 浏览: 154
这是一个 Java Servlet 中的过滤器,用于拦截访问 "/admin/*" 路径下的请求。它检查 Session 中是否存在一个名为 "user" 的属性,如果该属性不存在或者对应的用户不是管理员,则该请求会被重定向到 "../index.action" 路径下。如果用户是管理员,则该请求会通过,继续向下传递。
相关问题
package com.gcx.reggie.filter; import com.alibaba.fastjson.JSON; import com.gcx.reggie.common.R; import com.sun.org.apache.xerces.internal.impl.xs.XSAttributeUseImpl; import lombok.SneakyThrows; import lombok.extern.slf4j.Slf4j; import org.springframework.util.AntPathMatcher; import javax.servlet.*; import javax.servlet.annotation.WebFilter; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; @WebFilter(filterName = "loginCheckFilter",urlPatterns="/*") @Slf4j public class LoginCheckFilter implements Filter { public static AntPathMatcher PATH_MATCHER = new AntPathMatcher(); @SneakyThrows @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) servletRequest; HttpServletResponse response = (HttpServletResponse) servletResponse; String requestURI = request.getRequestURI(); String[] urls = new String[]{ "/employee/login", "/employee/logout", "/backend/**", "/front/**" }; boolean check=check(urls,requestURI); if(check) { filterChain.doFilter(request, response); return; } if(request.getSession().getAttribute("emplyee")!=null){ filterChain.doFilter(request, response); return; } response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN"))); return; } public boolean check(String[] urls, String requestURI) { for (String url : urls) { boolean match = PATH_MATCHER.match(url, requestURI); if(match==true) return true; } return false; } }
<think>好的,我现在需要帮助用户理解Spring Boot中自定义登录检查过滤器LoginCheckFilter的实现原理及常见问题。首先,用户提到了他们参考了三个引用,这些引用主要涉及过滤器的两种注册方式、ZuulFilter的使用以及启动类注解的问题。我需要结合这些信息来构建回答。
首先,我需要确认LoginCheckFilter的实现原理。根据引用[1],过滤器可以通过FilterRegistrationBean注册或者使用@WebFilter注解。引用[3]提到需要在启动类添加@ServletComponentScan来扫描Servlet组件,所以如果用户使用注解方式,这一点很重要。另外,引用[2]中的ZuulFilter是特定于Zuul的,但用户的问题是关于普通的过滤器,所以可能不需要这部分,但可以提到类似的方法,比如重写doFilter方法。
接下来,实现原理部分需要分步骤说明:创建过滤器类、配置过滤规则、注册过滤器。这里需要确保用户知道如何正确使用@WebFilter和配置urlPatterns,以及注册的方式。可能常见的问题是urlPatterns配置错误导致过滤器不生效,或者忘记添加@ServletComponentScan注解,导致过滤器未被扫描到。
然后,常见问题部分需要考虑用户可能遇到的情况。例如,过滤器顺序问题,因为根据引用[1],FilterRegistrationBean可以设置order,而默认顺序可能不符合需求。另外,静态资源被拦截也是一个常见问题,需要排除路径。还有登录页面本身被拦截,导致重定向循环,这也是需要处理的。
在注意事项中,需要强调放行登录相关路径,避免重复检查,以及正确使用过滤器的类型。例如,在Zuul中filterType是前置,但在普通Servlet过滤器中,可能通过doFilter内部逻辑控制。
最后,根据用户提供的引用,需要正确标注引用来源。例如,引用[1]提到两种注册方式,引用[3]提到启动类注解,这些都要在相应的地方标注。
现在需要组织这些内容,确保结构清晰,分点说明,并自然地插入引用标记。同时,检查是否有遗漏的问题点,比如Token验证失败的处理,或者跨域问题,不过用户的问题可能主要集中在登录检查的基本实现和常见配置错误上。
可能还需要考虑过滤器的链式调用,确保在doFilter中调用chain.doFilter()来继续执行后续过滤器或Servlet。如果用户忘记调用,会导致请求被阻塞,这也是一个常见错误。
总结下来,回答应该包括实现步骤、常见问题及解决方案、注意事项,并正确引用提供的资料。同时,生成的相关问题需要围绕实现细节、配置优化和问题排查展开。</think>### Spring Boot 自定义登录检查过滤器 LoginCheckFilter 实现原理及常见问题
#### 一、实现原理
1. **过滤器定义**
自定义过滤器需继承`javax.servlet.Filter`接口,并重写`doFilter`方法实现登录检查逻辑。例如:
```java
@WebFilter(filterName = "LoginCheckFilter", urlPatterns = "/*")
public class LoginCheckFilter implements Filter {
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse res = (HttpServletResponse) response;
String uri = req.getRequestURI();
// 放行登录、静态资源等路径
if (uri.contains("/login") || uri.contains("/static")) {
chain.doFilter(request, response);
return;
}
// 检查Session或Token
if (req.getSession().getAttribute("user") == null) {
res.sendRedirect("/login");
return;
}
chain.doFilter(request, response);
}
}
```
关键点:
- 使用`@WebFilter`注解定义过滤路径(需配合`@ServletComponentScan`)[^3]。
- 通过`FilterChain`控制请求放行或拦截。
2. **过滤器注册**
- **方式1**:通过`FilterRegistrationBean`显式注册(推荐)[^1]:
```java
@Configuration
public class FilterConfig {
@Bean
public FilterRegistrationBean<LoginCheckFilter> loginFilter() {
FilterRegistrationBean<LoginCheckFilter> bean = new FilterRegistrationBean<>();
bean.setFilter(new LoginCheckFilter());
bean.addUrlPatterns("/*");
bean.setOrder(1); // 设置优先级
return bean;
}
}
```
- **方式2**:使用`@WebFilter`+`@ServletComponentScan`注解自动扫描[^3]。
3. **核心逻辑**
在`doFilter`中判断用户会话(如Session或Token)是否存在:
- 若存在,放行请求。
- 若不存在,重定向到登录页或返回未登录错误[^2]。
---
#### 二、常见问题及解决方案
1. **过滤器未生效**
- **原因1**:未添加`@ServletComponentScan`注解(若使用`@WebFilter`)。
**解决**:在启动类添加`@ServletComponentScan`。
- **原因2**:URL路径匹配错误。
**解决**:检查`urlPatterns`是否覆盖目标路径,如`/*`表示拦截所有请求。
2. **过滤器执行顺序问题**
- **现象**:多个过滤器执行顺序不符合预期。
**解决**:通过`FilterRegistrationBean.setOrder()`显式设置优先级[^1]。
3. **静态资源被拦截**
- **解决**:在过滤器中排除静态资源路径:
```java
if (uri.contains("/css/") || uri.contains("/js/")) {
chain.doFilter(request, response);
return;
}
```
4. **重定向循环**
- **原因**:登录页面本身被过滤器拦截。
**解决**:在过滤器中明确放行登录相关路径:
```java
if (uri.endsWith("/login.html")) {
chain.doFilter(request, response);
return;
}
```
---
#### 三、注意事项
1. **会话管理**
- 若使用Token,需在请求头或Cookie中读取并验证(参考ZuulFilter的`run`方法逻辑)。
2. **性能优化**
- 避免在过滤器中执行耗时操作(如数据库查询),必要时使用缓存。
3. **跨域问题**
- 若前端与后端分离,需在过滤器中处理CORS头部(如`Access-Control-Allow-Origin`)。
---
package com.os.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); } } package com.os.config; import com.os.filter.JwtAuthenticationFilter; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.HttpMethod; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.config.Customizer; import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; 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.security.config.http.SessionCreationPolicy; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.web.AuthenticationEntryPoint; import org.springframework.security.web.access.AccessDeniedHandler; import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; import javax.annotation.Resource; @Configuration @EnableWebSecurity @EnableGlobalMethodSecurity(prePostEnabled = true) public class SecurityConfig extends WebSecurityConfigurerAdapter { @Resource private JwtAuthenticationFilter jwtAuthenticationFilter; @Resource private AuthenticationEntryPoint authenticationEntryPoint; @Resource private AccessDeniedHandler accessDeniedHandler; @Override protected void configure(HttpSecurity http) throws Exception { http .csrf().disable() .cors().and() //开启跨域 .authorizeRequests() .antMatchers("/user/user/login", "/user/user/register", "/user/user/retrievePassword", "/common/sendVerificationCode", "/common/sendRetrievePasswordCode").anonymous() .antMatchers(HttpMethod.OPTIONS, "/**").permitAll() .anyRequest().authenticated() .and() .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS); //添加过滤器 http.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class); //配置异常处理 http.exceptionHandling() .authenticationEntryPoint(authenticationEntryPoint) .accessDeniedHandler(accessDeniedHandler); } @Bean public BCryptPasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } @Override @Bean public AuthenticationManager authenticationManagerBean() throws Exception { return super.authenticationManagerBean(); } } 这是我的跨域配置和security配置,为什么不能正确进行跨域请求
<think>嗯,用户提供了两个Java配置类,分别是跨域配置和Spring Security配置,但遇到了跨域请求无法正常工作的问题。我需要仔细分析可能的原因。
首先看CorsConfig类。它实现了WebMvcConfigurer,并重写了addCorsMappings方法。这里允许所有路径的跨域,使用allowedOriginPatterns("*"),同时允许凭证(allowCredentials(true))。不过,我记得当使用allowCredentials(true)时,不能使用allowedOrigins("*"),因为浏览器出于安全考虑不允许同时使用通配符和凭证。虽然用户这里用的是allowedOriginPatterns,可能需要检查Spring版本是否支持这种写法。allowedOriginPatterns是在Spring 5.3之后引入的,支持更灵活的模式匹配,但即使这样,当允许凭证时,是否允许使用通配符?
接下来是SecurityConfig类,继承自WebSecurityConfigurerAdapter。在configure方法中,调用了.cors().and(),这应该是启用了Spring Security的CORS支持。但问题可能出在这里:如果CorsConfig已经配置了全局CORS,但Spring Security的CORS配置可能需要单独处理。有时候,即使全局CORS配置正确,Spring Security的过滤器链可能会覆盖这些设置,导致跨域请求被拦截。特别是对于需要认证的请求,Spring Security可能会优先处理,这时候需要确保CORS配置被正确应用到Security过滤器链中。
另外,用户可能没有将CorsConfig正确注册为一个Bean,或者在Spring Security的配置中没有正确启用CORS。虽然用户已经使用了@Configuration注解,应该会被扫描到,但可能需要确认是否存在多个CORS配置冲突的情况。
再检查HTTP方法,用户配置了allowedMethods包括GET、POST、DELETE、PUT,但可能遗漏了OPTIONS方法。不过,在SecurityConfig中,用户特别允许了所有OPTIONS请求的预检(preflight)请求,即.antMatchers(HttpMethod.OPTIONS, "/**").permitAll(),这应该处理了OPTIONS请求的问题。但跨域预检请求需要正确响应,可能还需要CORS配置中的allowedMethods包含OPTIONS方法,或者在Security配置中确保OPTIONS请求不被拦截。
还有一个可能性是,当浏览器发起跨域请求时,如果携带了认证信息(比如JWT token),而服务器返回的响应头中没有正确的Access-Control-Allow-Origin,或者通配符被拒绝。这时候即使配置了allowedOriginPatterns("*"),当allowCredentials为true时,可能需要具体指定允许的来源,而不是使用通配符。比如,应该设置具体的域名,如allowedOriginPatterns("https://example.com"),而不是"*"。
另外,检查Security的配置中是否关闭了csrf,这里已经调用了http.csrf().disable(),是正确的,因为跨域请求容易受到CSRF攻击,但禁用后可以减少配置复杂度。
总结可能的问题点:
1. allowedOriginPatterns("*")与allowCredentials(true)同时存在,导致浏览器拒绝请求。
2. Spring Security的CORS配置没有正确使用全局CORS配置,需要确认是否在Security中正确启用。
3. 预检请求的处理可能存在问题,虽然配置了OPTIONS放行,但CORS配置中的allowedMethods是否包含OPTIONS?
可能的解决方案:
1. 将allowedOriginPatterns("*")替换为具体的域名,或使用allowedOriginPatterns,但可能需要处理凭证的问题。
2. 检查Spring版本是否支持allowedOriginPatterns,并确认其与allowCredentials的兼容性。
3. 确保Spring Security的CORS配置引用了全局的CORS配置,或者在Security配置中显式配置CORS。</think>你的跨域配置存在几个关键问题,需要按以下步骤调整:
---
### 一、**CORS 配置冲突分析**
#### 1. **`allowedOriginPatterns("*")` 与 `allowCredentials(true)` 不兼容**
- **问题**:当启用凭证(`allowCredentials(true)`)时,浏览器禁止使用通配符 `*` 作为 `allowedOrigins`。需明确指定允许的域名。
- **解决**:替换为具体域名或动态匹配:
```java
.allowedOriginPatterns("http://localhost:8080", "https://yourdomain.com")
// 或动态匹配(需确保安全)
.allowedOriginPatterns("http://*.example.com")
```
#### 2. **未包含 `OPTIONS` 方法**
- **问题**:预检请求(Preflight)会使用 `OPTIONS` 方法,但你的配置仅允许 `GET, POST, DELETE, PUT`。
- **解决**:在 `allowedMethods` 中添加 `OPTIONS`:
```java
.allowedMethods("GET", "POST", "DELETE", "PUT", "OPTIONS")
```
---
### 二、**Spring Security 配置调整**
#### 1. **显式启用全局 CORS 配置**
- **问题**:Spring Security 默认会覆盖全局 CORS 配置。
- **解决**:在 `SecurityConfig` 中通过 `cors(Customizer.withDefaults())` 强制使用全局配置:
```java
http
.csrf().disable()
.cors(Customizer.withDefaults()) // 启用全局 CORS
.authorizeRequests()
...
```
#### 2. **确保 `OPTIONS` 请求放行**
- 你的配置已正确放行 `OPTIONS` 请求,无需修改:
```java
.antMatchers(HttpMethod.OPTIONS, "/**").permitAll()
```
---
### 三、**完整修正后的代码**
#### 1. **跨域配置(CorsConfig.java)**
```java
@Configuration
public class CorsConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOriginPatterns("http://localhost:*", "https://yourdomain.com") // 按需替换域名
.allowCredentials(true)
.allowedMethods("GET", "POST", "DELETE", "PUT", "OPTIONS")
.allowedHeaders("*")
.maxAge(3600);
}
}
```
#### 2. **安全配置(SecurityConfig.java)**
```java
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.cors(Customizer.withDefaults()) // 关键调整:强制使用全局 CORS
.authorizeRequests()
.antMatchers("/user/user/login", "/user/user/register").anonymous()
.antMatchers(HttpMethod.OPTIONS, "/**").permitAll()
.anyRequest().authenticated()
.and()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
// 其他配置(过滤器、异常处理)保持不变
}
}
```
---
### 四、**验证步骤**
1. **检查浏览器控制台报错**:查看是否存在 `CORS policy` 相关错误。
2. **使用 Postman 或 curl 测试**:确认预检请求(OPTIONS)返回正确的 `Access-Control-Allow-*` 头。
3. **验证凭证传递**:确保请求头包含 `Authorization` 时,响应头包含 `Access-Control-Allow-Credentials: true`。
通过以上调整,跨域问题应被解决。如果仍有异常,请提供具体错误信息以便进一步排查。
阅读全文
相关推荐






