Spring Security介绍(三)过滤器(2)自定义

除了使用security自带的过滤器链,我们还可以自定义过滤器拦截器。

下面看下自定义的和security自带的执行顺序。

一、总结

1、自定义过滤器:

一般自定义fliter都是:

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;import javax.servlet.*;
import java.io.IOException;@Component
@Slf4j
public class UrlFilter implements Filter {@Overridepublic void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {log.info("进入UrlFilter");filterChain.doFilter(servletRequest,servletResponse);}
}

但是结合spring security,这样的filter不会被执行, 需要修改为继承OncePerRequestFilter

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;import java.io.IOException;@Component
@Slf4j
public class UrlFilter extends OncePerRequestFilter {@Overrideprotected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, jakarta.servlet.FilterChain filterChain) throws jakarta.servlet.ServletException, IOException {log.info("进入UrlFilter");filterChain.doFilter(request,response);}
}
2、执行顺序
2.1、默认顺序:

security自带的过滤器链-->自定义过滤器-->自定义拦截器。

2.2、修改自定义interceptor顺序

修改在WebMvcConfigurer中注册的顺序即可。

2.3、修改自定义filter顺序

加@Order()注解,在注解中加入数字,数字越小,优先级越高,最先执行。其中这个数字可以:

(1)自定义

@Component
@Order(1)
public class XxxFilter extends OncePerRequestFilter{}@Component
@Order(2)
public class Xxx1Filter extends OncePerRequestFilter{}

这时执行的顺序是: security自带的过滤器链-->自定义过滤器的顺序-->自定义拦截器的顺序。

(2)使用枚举

源码:

1)HIGHEST_PRECEDENCE

代表这个过滤器在众多过滤器中级别最高,也就是过滤的时候最先执行,这时执行的顺序为:

自定义过滤器的顺序--> security自带的过滤器链-->自定义拦截器的顺序。 

2)LOWEST_PRECEDENCE

表示级别最低,最后执行过滤操作。

2.4、配置文件修改自定义filter顺序

filter的执行顺序除了可以用上面的@Order注解外,还可以通过配置文件设置,这时配置文件设置的优先级--》注解设置的优先级。如我两个filter都设置为Ordered.HIGHEST_PRECEDENCE + 1,其中一个在配置文件设置的,另外一个通过注解设置的,这时配置文件设置的那个会先执行。

package com.demo.security.config;import com.demo.security.filter.UrlTwoFilter;
import com.demo.security.interceptor.ParamInterceptor;
import com.demo.security.interceptor.ParamOneInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;import java.util.List;@Configuration
public class WebMvcConfig implements WebMvcConfigurer {@Autowiredprivate ParamInterceptor paramInterceptor;@Autowiredprivate ParamOneInterceptor paramOneInterceptor;@Autowiredprivate UrlTwoFilter twoFilter;@Overridepublic void addInterceptors(InterceptorRegistry registry) {registry.addInterceptor(paramOneInterceptor);registry.addInterceptor(paramInterceptor).addPathPatterns("/**");//registry.addInterceptor(paramOneInterceptor);}@Beanpublic FilterRegistrationBean<UrlTwoFilter> getIpFilter() {FilterRegistrationBean<UrlTwoFilter> registrationBean = new FilterRegistrationBean<>();registrationBean.setFilter(twoFilter);registrationBean.setEnabled(true);registrationBean.setOrder(Ordered.HIGHEST_PRECEDENCE + 1);registrationBean.setUrlPatterns(List.of("/*"));return registrationBean;}
}
@Component
@Slf4j
//@Order(1)
@Order(Ordered.HIGHEST_PRECEDENCE+1)
public class UrlOneFilter extends OncePerRequestFilter

下面通过demo来验证下 

二、demo

1、使用security过滤器
(1)编写过滤器
package com.demo.security.filter;import com.demo.security.constant.UserConstants;
import com.demo.security.dto.UserDTO;
import com.demo.security.util.JwtUtil;
import com.demo.security.util.RedisClient;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.entity.ContentType;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.util.StringUtils;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Map;
@Slf4j
public class LoginFilter extends UsernamePasswordAuthenticationFilter {private AuthenticationManager authenticationManager;private RedisClient redisClient;public LoginFilter(AuthenticationManager authenticationManager, RedisClient redisClient) {//super(new AntPathRequestMatcher("/login", "POST"));this.authenticationManager = authenticationManager;this.redisClient = redisClient;}@Overridepublic Authentication attemptAuthentication(HttpServletRequest req, HttpServletResponse res) throws AuthenticationException {try {logger.info("进入LoginFilter");String userName = req.getParameter("userName");String passWord = req.getParameter("passWord");if (StringUtils.isEmpty(userName)) {throw new UsernameNotFoundException("请输入账号");}if (StringUtils.isEmpty(passWord)) {throw new UsernameNotFoundException("请输入密码");}//验证用户名密码是否正确Map<String, String> userMap = UserConstants.getUsers();if(!userMap.keySet().contains(userName)){throw new UsernameNotFoundException("用户不存在");}if(!passWord.equals(userMap.get(userName))){throw new UsernameNotFoundException("密码错误");}//这里权限返回空,由后面的授权过滤器查询return authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(userName, passWord, new ArrayList<>()));} catch (UsernameNotFoundException e) {//返回错误信息res.setCharacterEncoding("UTF-8");res.setContentType("application/text;charset=utf-8");try {res.getWriter().write(e.getMessage());} catch (IOException e1) {e1.printStackTrace();}return null;}catch (Exception e){throw new RuntimeException(e);}}@Overrideprotected void successfulAuthentication(HttpServletRequest request,HttpServletResponse res,jakarta.servlet.FilterChain chain,Authentication authResult)throws IOException, jakarta.servlet.ServletException {UserDTO userDTO = (UserDTO) authResult.getPrincipal();String userName = userDTO.getUsername();String password = userDTO.getPassword();String jwtToken = JwtUtil.sign(userName, password);//缓存到redis中redisClient.set(userName,jwtToken);//返回res.setContentType(ContentType.TEXT_HTML.toString());res.getWriter().write(jwtToken);}
}
package com.demo.security.filter;import com.demo.security.util.JwtUtil;
import com.demo.security.util.RedisClient;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
import org.springframework.util.StringUtils;import java.io.IOException;
@Slf4j
public class TokenAuthenticationFilter extends BasicAuthenticationFilter {private RedisClient redisClient;private UserDetailsService userDetailsService;public TokenAuthenticationFilter(AuthenticationManager authenticationManager, RedisClient redisClient, UserDetailsService userDetailsService) {super(authenticationManager);this.redisClient = redisClient;this.userDetailsService = userDetailsService;}@Overrideprotected void doFilterInternal(HttpServletRequest req, HttpServletResponse res, FilterChain chain) throws IOException, ServletException {logger.info("登陆成功后访问,url={}"+req.getRequestURI());String token = req.getHeader("token");res.setCharacterEncoding("UTF-8");res.setContentType("application/text;charset=utf-8");if(StringUtils.isEmpty(token)){logger.info("登陆成功后访问,url={},token为空"+req.getRequestURI());res.getWriter().write("token为空");return;}//1、token是否正确,是否能反解析出userNameString userName = JwtUtil.getUsername(token);if(StringUtils.isEmpty(userName)){logger.info("登陆成功后访问,url={},token错误"+req.getRequestURI());res.getWriter().write("token错误");return;}//2、验证token是否过期String redisToken = redisClient.get(userName);if(StringUtils.isEmpty(redisToken) || !token.equals(redisToken)){logger.info("登陆成功后访问,url={},token过期"+req.getRequestURI());res.getWriter().write("token过期");return;}UserDetails currentUser = userDetailsService.loadUserByUsername(userName);UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(currentUser,null,currentUser.getAuthorities());SecurityContextHolder.getContext().setAuthentication(authentication);chain.doFilter(req, res);}
}
(2)注册到过滤器链中
package com.demo.security.config;//import com.demo.security.filter.AuthenticationFilter;
//import com.demo.security.filter.LoginFilter;
import com.demo.security.filter.LoginFilter;
import com.demo.security.filter.TokenAuthenticationFilter;
import com.demo.security.util.RedisClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.authentication.configuration.GlobalAuthenticationConfigurerAdapter;
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.configurers.AbstractHttpConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;import static io.netty.util.CharsetUtil.encoder;@EnableWebSecurity
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityWebConfig {@Autowiredprivate RedisClient redisClient;@Autowiredprivate UserDetailsService userDetailsService;@Beanpublic PasswordEncoder passwordEncoder() {return new MyPasswordEncoder();}@Beanpublic AuthenticationManager authenticationManager(AuthenticationConfiguration authConfig) throws Exception {return authConfig.getAuthenticationManager();}@Beanpublic SecurityFilterChain configure(HttpSecurity http, AuthenticationManager authenticationManager) throws Exception {http.csrf(AbstractHttpConfigurer::disable);http.headers(AbstractHttpConfigurer::disable);http.sessionManagement(sessionManagement -> {sessionManagement.sessionCreationPolicy(SessionCreationPolicy.STATELESS);});http.authorizeRequests().anyRequest().authenticated().and()//1、登陆、退出url,均由前端拦截器控制,这里注释掉。//1.1、前端拦截器中判断缓存token为空,为空则post请求访问/login,目的是进入LoginFilter获取token//1.2、不为空则带token访问接口,如果AuthenticationFilter拦截token不合法则根据错误码跳转到登陆页面,重复1.1的操作//.logout().logoutUrl("/logout").and()//2、身份认证filter,访问系统(除了白名单接口)需要先登陆。post请求/login接口会进入这个拦截器// 校验用户名密码是否正确,正确返回token给前端,不正确则返回异常信息.addFilterBefore(new LoginFilter(authenticationManager,redisClient), LoginFilter.class)//3、授权filer,authenticationManager为BasicAuthenticationFilter的必传参数。所有的接口都会走到这里// 根据用户id查询权限,连同身份一起塞入SecurityContextHolder全局变量,后面获取用户信息则直接从SecurityContextHolder中get.addFilterBefore(new TokenAuthenticationFilter(authenticationManager,redisClient,userDetailsService),TokenAuthenticationFilter.class);return http.build();}}
2、自定义过滤器拦截器
2.1、过滤器
package com.demo.security.filter;import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;import java.io.IOException;@Component
@Slf4j
public class UrlFilter extends OncePerRequestFilter {@Overrideprotected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, jakarta.servlet.FilterChain filterChain) throws jakarta.servlet.ServletException, IOException {log.info("进入UrlFilter");filterChain.doFilter(request,response);}
}
package com.demo.security.filter;import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;import java.io.IOException;@Component
@Slf4j
public class UrlOneFilter extends OncePerRequestFilter {@Overrideprotected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, jakarta.servlet.FilterChain filterChain) throws jakarta.servlet.ServletException, IOException {log.info("进入UrlFilter-one");filterChain.doFilter(request,response);}
}
  2.2、拦截器

(1)编写拦截器

package com.demo.security.interceptor;import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;@Component
@Slf4j
public class ParamInterceptor implements HandlerInterceptor {@Overridepublic boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {log.info("进入ParamInterceptor");return true;}
}
package com.demo.security.interceptor;import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;@Component
@Slf4j
public class ParamOneInterceptor implements HandlerInterceptor {@Overridepublic boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {log.info("进入ParamInterceptor-one");return true;}
}

(2)注册

package com.demo.security.config;import com.demo.security.interceptor.ParamInterceptor;
import com.demo.security.interceptor.ParamOneInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;@Configuration
public class WebMvcConfig implements WebMvcConfigurer {@Autowiredprivate ParamInterceptor paramInterceptor;@Autowiredprivate ParamOneInterceptor paramOneInterceptor;@Overridepublic void addInterceptors(InterceptorRegistry registry) {registry.addInterceptor(paramInterceptor).addPathPatterns("/**");registry.addInterceptor(paramOneInterceptor);}
}
3、测试默认顺序

(1)LoginFilter为特定情况下才能进入(/login的post请求),认证成功即返回:

访问localhost:2222/securityDemo/login?userName=zs&passWord=123后台打印

2024-04-27T09:14:57.210+08:00  INFO 14836 --- [nio-2222-exec-3] com.demo.security.filter.LoginFilter     : 进入LoginFilter

(2)访问其他接口,如localhost:2222/securityDemo/menu/test

如果沒有登录,在TokenAuthenticationFilter就返回了,控制台打印

2024-04-27T09:31:01.715+08:00  INFO 37920 --- [nio-2222-exec-3] c.d.s.filter.TokenAuthenticationFilter   : 登陆成功后访问,url={}/securityDemo/menu/test
2024-04-27T09:31:01.734+08:00  INFO 37920 --- [nio-2222-exec-3] c.d.s.filter.TokenAuthenticationFilter   : 登陆成功后访问,url={},token过期/securityDemo/menu/test

如果登录了,后台打印

2024-04-27T09:32:56.046+08:00  INFO 37920 --- [nio-2222-exec-7] c.d.s.filter.TokenAuthenticationFilter   : 登陆成功后访问,url={}/securityDemo/menu/test
2024-04-27T09:32:56.064+08:00  INFO 37920 --- [nio-2222-exec-7] com.demo.security.filter.UrlFilter       : 进入UrlFilter
2024-04-27T09:32:56.064+08:00  INFO 37920 --- [nio-2222-exec-7] com.demo.security.filter.UrlOneFilter    : 进入UrlFilter-one
2024-04-27T09:32:56.070+08:00  INFO 37920 --- [nio-2222-exec-7] c.d.s.interceptor.ParamInterceptor       : 进入ParamInterceptor
2024-04-27T09:32:56.070+08:00  INFO 37920 --- [nio-2222-exec-7] c.d.s.interceptor.ParamOneInterceptor    : 进入ParamInterceptor-one

可以看到,执行顺序是security自带的过滤器链-->自定义过滤器-->自定义拦截器

4、修改执行顺序

下面修改自定义的过滤器拦截器的顺序:

4.1、拦截器

在WebMvcConfigurer中修改注册顺序

package com.demo.security.config;import com.demo.security.interceptor.ParamInterceptor;
import com.demo.security.interceptor.ParamOneInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;@Configuration
public class WebMvcConfig implements WebMvcConfigurer {@Autowiredprivate ParamInterceptor paramInterceptor;@Autowiredprivate ParamOneInterceptor paramOneInterceptor;@Overridepublic void addInterceptors(InterceptorRegistry registry) {registry.addInterceptor(paramOneInterceptor);registry.addInterceptor(paramInterceptor).addPathPatterns("/**");//registry.addInterceptor(paramOneInterceptor);}
}
4.2、过滤器
package com.demo.security.filter;import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;import java.io.IOException;@Component
@Slf4j
@Order(2)
public class UrlFilter extends OncePerRequestFilter {@Overrideprotected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, jakarta.servlet.FilterChain filterChain) throws jakarta.servlet.ServletException, IOException {log.info("进入UrlFilter");filterChain.doFilter(request,response);}
}
package com.demo.security.filter;import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;import java.io.IOException;@Component
@Slf4j
@Order(1)
public class UrlOneFilter extends OncePerRequestFilter {@Overrideprotected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, jakarta.servlet.FilterChain filterChain) throws jakarta.servlet.ServletException, IOException {log.info("进入UrlFilter-one");filterChain.doFilter(request,response);}
}

 再次测试,可以看到执行顺序已经修改了

2024-04-27T09:39:09.419+08:00  INFO 65540 --- [nio-2222-exec-3] c.d.s.filter.TokenAuthenticationFilter   : 登陆成功后访问,url={}/securityDemo/menu/test
2024-04-27T09:39:09.471+08:00  INFO 65540 --- [nio-2222-exec-3] com.demo.security.filter.UrlOneFilter    : 进入UrlFilter-one
2024-04-27T09:39:09.471+08:00  INFO 65540 --- [nio-2222-exec-3] com.demo.security.filter.UrlFilter       : 进入UrlFilter
2024-04-27T09:39:09.476+08:00  INFO 65540 --- [nio-2222-exec-3] c.d.s.interceptor.ParamOneInterceptor    : 进入ParamInterceptor-one
2024-04-27T09:39:09.476+08:00  INFO 65540 --- [nio-2222-exec-3] c.d.s.interceptor.ParamInterceptor       : 进入ParamInterceptor

执行顺序为:security自带的过滤器链-->自定义过滤器的顺序-->自定义拦截器的顺序。

5、设置自定义filter优先级最高

(1)只修改一个

package com.demo.security.filter;import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;import java.io.IOException;@Component
@Slf4j
//所有filter中优先级最高
@Order(Ordered.HIGHEST_PRECEDENCE+1)
public class UrlFilter extends OncePerRequestFilter {@Overrideprotected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, jakarta.servlet.FilterChain filterChain) throws jakarta.servlet.ServletException, IOException {log.info("进入UrlFilter");filterChain.doFilter(request,response);}
}

 另外一个不变:

@Component
@Slf4j
@Order(1)
public class UrlOneFilter extends OncePerRequestFilter

这时访问登录接口后台打印:

2024-04-28T11:11:31.846+08:00  INFO 37052 --- [nio-2222-exec-5] com.demo.security.filter.UrlFilter       : 进入UrlFilter
2024-04-28T11:11:31.847+08:00  INFO 37052 --- [nio-2222-exec-5] com.demo.security.filter.LoginFilter     : 进入LoginFilter

再访问localhost:2222/securityDemo/menu/test,后台打印:

2024-04-28T11:10:53.685+08:00  INFO 37052 --- [nio-2222-exec-4] com.demo.security.filter.UrlFilter       : 进入UrlFilter
2024-04-28T11:10:53.686+08:00  INFO 37052 --- [nio-2222-exec-4] c.d.s.filter.TokenAuthenticationFilter   : 登陆成功后访问,url={}/securityDemo/menu/test
2024-04-28T11:10:53.688+08:00  INFO 37052 --- [nio-2222-exec-4] com.demo.security.filter.UrlOneFilter    : 进入UrlFilter-one
2024-04-28T11:10:53.689+08:00  INFO 37052 --- [nio-2222-exec-4] c.d.s.interceptor.ParamOneInterceptor    : 进入ParamInterceptor-one
2024-04-28T11:10:53.689+08:00  INFO 37052 --- [nio-2222-exec-4] c.d.s.interceptor.ParamInterceptor       : 进入ParamInterceptor

可以看到,自定义的filter比security自带的过滤器链顺序都高。

(2)再把另外一个filter优先级也提高:

@Component
@Slf4j
//@Order(1)
@Order(Ordered.HIGHEST_PRECEDENCE+2)
public class UrlOneFilter extends OncePerRequestFilter

访问登录接口localhost:2222/securityDemo/login?userName=zs&passWord=123

2024-04-28T11:14:35.904+08:00  INFO 56456 --- [nio-2222-exec-2] o.a.c.c.C.[.[localhost].[/securityDemo]  : Initializing Spring DispatcherServlet 'dispatcherServlet'
2024-04-28T11:14:35.904+08:00  INFO 56456 --- [nio-2222-exec-2] o.s.web.servlet.DispatcherServlet        : Initializing Servlet 'dispatcherServlet'
2024-04-28T11:14:35.904+08:00  INFO 56456 --- [nio-2222-exec-2] o.s.web.servlet.DispatcherServlet        : Completed initialization in 0 ms
2024-04-28T11:14:35.904+08:00  INFO 56456 --- [nio-2222-exec-2] com.demo.security.filter.UrlFilter       : 进入UrlFilter
2024-04-28T11:14:35.904+08:00  INFO 56456 --- [nio-2222-exec-2] com.demo.security.filter.UrlOneFilter    : 进入UrlFilter-one
2024-04-28T11:14:35.919+08:00  INFO 56456 --- [nio-2222-exec-2] com.demo.security.filter.LoginFilter     : 进入LoginFilter

再访问localhost:2222/securityDemo/menu/test,后台打印:

2024-04-28T11:15:30.019+08:00  INFO 56456 --- [nio-2222-exec-5] com.demo.security.filter.UrlFilter       : 进入UrlFilter
2024-04-28T11:15:30.019+08:00  INFO 56456 --- [nio-2222-exec-5] com.demo.security.filter.UrlOneFilter    : 进入UrlFilter-one
2024-04-28T11:15:30.020+08:00  INFO 56456 --- [nio-2222-exec-5] c.d.s.filter.TokenAuthenticationFilter   : 登陆成功后访问,url={}/securityDemo/menu/test
2024-04-28T11:15:30.021+08:00  INFO 56456 --- [nio-2222-exec-5] c.d.s.interceptor.ParamOneInterceptor    : 进入ParamInterceptor-one
2024-04-28T11:15:30.021+08:00  INFO 56456 --- [nio-2222-exec-5] c.d.s.interceptor.ParamInterceptor       : 进入ParamInterceptor
6、测试相同Order顺序

再加一个filter,且优先级都设置成相同的:

@Component
@Slf4j
//所有filter中优先级最高
@Order(Ordered.HIGHEST_PRECEDENCE+1)
public class UrlFilter extends OncePerRequestFilter
@Component
@Slf4j
//@Order(1)
@Order(Ordered.HIGHEST_PRECEDENCE+1)
public class UrlOneFilter extends OncePerRequestFilter

@Component
@Slf4j
@Order(Ordered.HIGHEST_PRECEDENCE+1)
public class UrlTwoFilter extends OncePerRequestFilter

测试,执行顺序为:

2024-04-28T11:28:38.217+08:00  INFO 41668 --- [nio-2222-exec-5] com.demo.security.filter.UrlFilter       : 进入UrlFilter
2024-04-28T11:28:38.217+08:00  INFO 41668 --- [nio-2222-exec-5] com.demo.security.filter.UrlOneFilter    : 进入UrlFilter-one
2024-04-28T11:28:38.218+08:00  INFO 41668 --- [nio-2222-exec-5] com.demo.security.filter.UrlTwoFilter    : 进入UrlFilter-two

现在将two放到配置文件中指定顺序:

package com.demo.security.config;import com.demo.security.filter.UrlTwoFilter;
import com.demo.security.interceptor.ParamInterceptor;
import com.demo.security.interceptor.ParamOneInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;import java.util.List;@Configuration
public class WebMvcConfig implements WebMvcConfigurer {@Autowiredprivate ParamInterceptor paramInterceptor;@Autowiredprivate ParamOneInterceptor paramOneInterceptor;@Autowiredprivate UrlTwoFilter twoFilter;@Overridepublic void addInterceptors(InterceptorRegistry registry) {registry.addInterceptor(paramOneInterceptor);registry.addInterceptor(paramInterceptor).addPathPatterns("/**");//registry.addInterceptor(paramOneInterceptor);}@Beanpublic FilterRegistrationBean<UrlTwoFilter> getIpFilter() {FilterRegistrationBean<UrlTwoFilter> registrationBean = new FilterRegistrationBean<>();registrationBean.setFilter(twoFilter);registrationBean.setEnabled(true);registrationBean.setOrder(Ordered.HIGHEST_PRECEDENCE + 1);registrationBean.setUrlPatterns(List.of("/*"));return registrationBean;}
}

再次查看执行顺序:

2024-04-28T11:31:22.754+08:00  INFO 18328 --- [nio-2222-exec-3] com.demo.security.filter.UrlTwoFilter    : 进入UrlFilter-two
2024-04-28T11:31:22.754+08:00  INFO 18328 --- [nio-2222-exec-3] com.demo.security.filter.UrlFilter       : 进入UrlFilter
2024-04-28T11:31:22.754+08:00  INFO 18328 --- [nio-2222-exec-3] com.demo.security.filter.UrlOneFilter    : 进入UrlFilter-one
2024-04-28T11:31:22.754+08:00  INFO 18328 --- [nio-2222-exec-3] c.d.s.filter.TokenAuthenticationFilter   : 登陆成功后访问,url={}/securityDemo/menu/test
2024-04-28T11:31:22.754+08:00  INFO 18328 --- [nio-2222-exec-3] c.d.s.interceptor.ParamOneInterceptor    : 进入ParamInterceptor-one
2024-04-28T11:31:22.754+08:00  INFO 18328 --- [nio-2222-exec-3] c.d.s.interceptor.ParamInterceptor       : 进入ParamInterceptor

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/diannao/5472.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

QT - 创建Qt Widgets Application项目

在Qt中结合OpenGL使用&#xff0c;可以创建一个Qt Widgets应用程序项目。在创建项目时&#xff0c;您可以选择使用OpenGL模板来生成一个已经集成了OpenGL的项目。这个模板会自动帮助您集成OpenGL和Qt&#xff0c;并生成一个基本的OpenGL窗口。您可以在这个窗口中进行OpenGL的开…

闭嘴,如果你遇到偏执型人格!头脑风暴:王阳明心学向内求——早读(逆天打工人爬取热门微信文章解读)

看我极限头脑风暴 引言Python 代码第一篇 洞见 偏执型人格&#xff1a;跟谁在一起&#xff0c;谁痛苦第二篇 人民日报 来啦新闻早班车要闻社会政策 结尾 若天意未许晴好时&#xff0c; 勿将雨声作悲泣。 不向外界寻怨尤&#xff0c; 反求诸己养性灵。 引言 五一劳动节 第一天就…

C语言(操作符)1

Hi~&#xff01;这里是奋斗的小羊&#xff0c;很荣幸各位能阅读我的文章&#xff0c;诚请评论指点&#xff0c;关注收藏&#xff0c;欢迎欢迎~~ &#x1f4a5;个人主页&#xff1a;小羊在奋斗 &#x1f4a5;所属专栏&#xff1a;C语言 本系列文章为个人学习笔记&#x…

区块链论文总结速读--CCF B会议 ICDCS 2023 共8篇

Conference&#xff1a;IEEE 43rd International Conference on Distributed Computing Systems (ICDCS) CCF level&#xff1a;CCF B Categories&#xff1a;Computer Architecture/Parallel and Distributed Computing/Storage Systems 计算机体系结构/并行与分布计算/存储…

【C语言】深入了解文件:简明指南

&#x1f308;个人主页&#xff1a;是店小二呀 &#x1f308;C语言笔记专栏&#xff1a;C语言笔记 &#x1f308;C笔记专栏&#xff1a; C笔记 &#x1f308;喜欢的诗句:无人扶我青云志 我自踏雪至山巅 文章目录 一、文件的概念1.1 文件名:1.2 程序文件和数据文件 二、数据文…

可靠的Mac照片恢复解决方案

当您在搜索引擎搜索中输入“Mac照片恢复”时&#xff0c;您将获得数以万计的结果。有很多Mac照片恢复解决方案声称他们可以在Mac OS下恢复丢失的照片。但是&#xff0c;并非互联网上的所有Mac照片恢复解决方案都可以解决您的照片丢失问题。而且您不应该花太多时间寻找可靠的Mac…

4月27日,上海Sui Meetup回顾与展望

活动吸引了超过200名报名者&#xff0c;其中的100多位技术爱好者亲临现场&#xff0c;一同见证了这一精彩时刻。 在这场为技术爱好者和开发者打造的盛会中&#xff0c;嘉宾们带来了内容丰富、见解独到的分享。 Sui 生态的活力与创新得到了充分展现。 在这场技术与创新的盛会…

74、堆-数组中的第K个最大元素

思路&#xff1a; 直接排序是可以的&#xff0c;但是时间复杂度不符合。可以使用优先队列&#xff0c;代码如下&#xff1a; class Solution {public int findKthLargest(int[] nums, int k) {if (numsnull||nums.length0||k<0||k>nums.length){return Integer.MAX_VAL…

CST电磁仿真局部网格设置与仿真结构不参与仿真设置【基础教程】

局部网格设置 使用Local Mesh功能在特定结构&#xff08;区域&#xff09;设置网格 Simulation > Mesh > Local Mesh Properties 仿真模型的构成部件尺寸和复杂度是非常多样的&#xff0c;如果以最复杂的部分为准来划分网格不复杂的部分也会生成非常稠密的网格&#x…

[Java、Android面试]_24_Compose为什么绘制要比XML快?(高频问答)

欢迎查看合集&#xff1a; Java、Android面试高频系列文章合集 本人今年参加了很多面试&#xff0c;也有幸拿到了一些大厂的offer&#xff0c;整理了众多面试资料&#xff0c;后续还会分享众多面试资料。 整理成了面试系列&#xff0c;由于时间有限&#xff0c;每天整理一点&am…

Linux操作系统·进程管理

一、什么是进程 1.作业和进程的概念 Linux是一个多用户多任务的操作系统。多用户是指多个用户可以在同一时间使用计算机系统&#xff1b;多任务是指Linux可以同时执行几个任务&#xff0c;它可以在还未执行完一个任务时又执行另一项任务。为了完成这些任务&#xff0c;系统上…

Android binder死亡通知机制

在Andorid 的binder系统中&#xff0c;当Bn端由于种种原因死亡时&#xff0c;需要通知Bp端&#xff0c;Bp端感知Bn端死亡后&#xff0c;做相应的处理。 使用 Bp需要先注册一个死亡通知&#xff0c;当Bn端死亡时&#xff0c;回调到Bp端。 1&#xff0c;java代码注册死亡通知 …

【webrtc】MessageHandler 9: 基于线程的消息处理:执行Port销毁自己

Port::Port 构造的时候,就触发了一个异步操作,但是这个操作是要在 thread 里执行的,因此要通过post 消息 MSG_DESTROY_IF_DEAD 到thread跑:port的创建并米有要求在thread中 但是port的析构却在thread里 这是为啥呢?

豆瓣9.7,这部Java神作第3版重磅上市!

Java 程序员们开年就有重磅好消息&#xff0c;《Effective Java 中文版&#xff08;原书第 3 版&#xff09;》要上市啦&#xff01; 该书的第1版出版于 2001 年&#xff0c;当时就在业界流传开来&#xff0c;受到广泛赞誉。时至今日&#xff0c;已热销近20年&#xff0c;本书第…

三维SDMTSP:GWO灰狼优化算法求解三维单仓库多旅行商问题,可以更改数据集和起点(MATLAB代码)

一、单仓库多旅行商问题 多旅行商问题&#xff08;Multiple Traveling Salesman Problem, MTSP&#xff09;是著名的旅行商问题&#xff08;Traveling Salesman Problem, TSP&#xff09;的延伸&#xff0c;多旅行商问题定义为&#xff1a;给定一个&#x1d45b;座城市的城市集…

CST Studio初级教程 五

本课程将实例讲解CST 3D建模。CST 3D 建模有三个途径&#xff1a;一种方法是用Brick、Sphere、Cone、Torus、Cylinder、Bond Wire指令绘制实体。第二种方法是用Extrude Face、Rotate Face、loft在已有模型基础上生成实体。第三种方法是&#xff0c;先用2D绘图指令绘制Curves&am…

Apache POI 在java中处理excel

介绍: Apache POI 是一个处理Miscrosoft Office各种文件格式的开源项目。简单来说就是&#xff0c;我们可以使用 POI 在 Java 程序中对Miscrosoft Office各种文件进行读写操作。 一般情况下&#xff0c;POI 都是用于操作 Excel 文件。 如何使用: 1.maven坐标引入 <depend…

Aker(安碁科技)晶振产品应用和选型

一、石英晶体振荡器简介 在电子电路系统中&#xff0c;特定的动作需要严格按照一定的顺序进行&#xff0c;以确保数据被正确处理和操作&#xff0c;时钟信号就成了系统工作的重要引导者。而且在多模块复杂电路系统中&#xff0c;为了确保不同功能模块能协调一致地工作&#xf…

你用过最好用的AI工具有哪些

一&#xff1a;介绍 随着科技的飞速发展&#xff0c;AI技术已经深入到我们生活的每一个角落&#xff0c;为我们提供了前所未有的便利和可能性。在众多AI工具中&#xff0c;有几种特别受到人们的喜爱&#xff0c;并且在各自的领域中产生了深远的影响。 1、AI绘画工具 改图鸭AI绘…

【HarmonyOS4学习笔记】《HarmonyOS4+NEXT星河版入门到企业级实战教程》课程学习笔记(七)

课程地址&#xff1a; 黑马程序员HarmonyOS4NEXT星河版入门到企业级实战教程&#xff0c;一套精通鸿蒙应用开发 &#xff08;本篇笔记对应课程第 14 节&#xff09; P14《13.ArkUI组件-自定义组件》 将可变部分封装成组件的成员变量&#xff1a; 1、首先给标题添加两个图标&am…