Spring-boot添加Interceptor进行认证验证

个人开发的基于内存的请求监控系统。欢迎star和一同参与https://github.com/standup-jb/tortoise

背景:自己在做一个Agile的管理系统,需要做到用户认证和页面拦截跳转。所以需要验证是否有Session和Cookie的信息。如果没有就重新定向到登录页面,然后为了这个问题各种在网上找解决方法,说到这里真的很生气呀。网上大家写博客真的是内容参差不齐,很多博客即不说清楚原理也不说清楚解决的方法。一边看一边生气,既然写出来给大家看就得要保证博客的质量吧。不然就是浪费时间,如果你只想是把博客当做是记事本的话,我建议用有道云笔记或许更好用。好了不说了,只希望大家可以写出高质量的博客共建和谐美好的IT社区。既然我自己都这么说了,我肯定要保证博客的质量了,下面我会用最详细让大家都能看到,而且保证可以解决。

问题重现:1、在登录之前不管是那个链接,都跳转到登录界面。

                  2、在登录之后如果认证成功会添加Session信息。

                  3、如果在有Session认证的情况下可以可以访问。

解决方法:我们先学习两个东西,HandlerInterceptor 和  WebMvcConfigurerAdapter

HandleIntercepotr: 在Spring中定义一个Interceptor是非常简单的,主要有两种方式:

第一种:实现HandlerInterceptor 接口,或者是继承实现了HandlerInterceptor 接口的类,例如HandlerInterceptorAdapter; 

### 配置自定义拦截器 为了在 `spring-boot-starter-security` 中配置自定义拦截器,可以创建一个类并实现 `OncePerRequestFilter` 接口来构建自定义过滤器。此方法允许更细粒度地控制HTTP请求处理过程中的行为。 ```java import org.springframework.stereotype.Component; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @Component public class CustomSecurityInterceptor extends OncePerRequestFilter { @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { // 自定义逻辑在此处编写 System.out.println("Custom security interceptor is processing the request."); // 继续链式调用其他过滤器或目标资源 filterChain.doFilter(request,response); } } ``` 接着,在Spring Security配置文件中注册这个新的过滤器: ```java 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.security.web.authentication.UsernamePasswordAuthenticationFilter; @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { private final CustomSecurityInterceptor customSecurityInterceptor; public SecurityConfig(CustomSecurityInterceptor customSecurityInterceptor){ this.customSecurityInterceptor=customSecurityInterceptor; } @Override protected void configure(HttpSecurity http) throws Exception{ http.addFilterBefore(customSecurityInterceptor, UsernamePasswordAuthenticationFilter.class); // 定义哪些URL需要被保护以及相应的访问权限 http.authorizeRequests() .antMatchers("/admin/**").hasRole("ADMIN") // 只有管理员角色才能访问/admin路径下的页面 .anyRequest().authenticated(); // 所有其它请求都需要认证后才可以访问 // 启动表单登录功能,默认会自动跳转到/login界面让用户输入用户名密码进行身份验证 http.formLogin(); } } ``` 上述代码展示了如何将自定义的安全拦截器集成至现有的Spring Security框架内,并设置特定的URL模式匹配规则[^1]。
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值