SpringBoot 拦截器

本文详细介绍了如何在Spring Boot项目中配置Spring Security进行安全控制,并结合JWT实现用户认证过程。通过示例代码展示了拦截器的配置、排除路径、JWT解密验证以及与Redis的交互,确保了系统的安全性。

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

package com.example.filter;

import java.io.IOException;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.example.constant.AuthConst;
import com.example.util.JedisUtil;
import com.example.util.JwtUtil;
import com.example.util.RSAUtil;

import redis.clients.jedis.Jedis;

@Configuration
public class WebSecurityConfig extends WebMvcConfigurerAdapter {
 
    public static final String SESSION_KEY="name";
 
    @Bean
    public SecurityInterceptor getSecurityInterceptor(){
        return  new SecurityInterceptor();
    }
    @Override
    public  void addInterceptors(InterceptorRegistry registry){
        InterceptorRegistration addInterceptor = registry.addInterceptor(getSecurityInterceptor());
 
        //排除配置
        addInterceptor.excludePathPatterns("/error");
        addInterceptor.excludePathPatterns("/login/**");
        addInterceptor.excludePathPatterns("/tologin");
        addInterceptor.excludePathPatterns("/index");
        addInterceptor.excludePathPatterns("/captcha");//排除验证码
        addInterceptor.excludePathPatterns("/css/**");
        addInterceptor.excludePathPatterns("/fonts/**");
        addInterceptor.excludePathPatterns("/img/**");
        addInterceptor.excludePathPatterns("/js/**");
        //拦截配置
        addInterceptor.addPathPatterns("/**/**");
    }
 
    private class SecurityInterceptor extends HandlerInterceptorAdapter {
        @Override
        public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)throws IOException{
            HttpSession session = request.getSession();
 
            Cookie[] cookies = request.getCookies(); //获取cookie数组
    		
    		for(Cookie cookie:cookies){//遍历cookie数组
    			 if ("tokenId".equals(cookie.getName())) {
    				
    				System.out.println("获取cookie的名字: " + cookie.getName());//获取cookie的名字
    				System.out.println("获取cookie的值: " + cookie.getValue()); //获取cookie的值
    				
    				// 从认证中心回跳的带有token的请求,有效则放行
    				//String token = request.getParameter(AuthConst.TOKEN);
    				String token = cookie.getValue();
    				if (token != null) {
    					//解密jwt并验证是否正确
    					boolean freeJwt = new JwtUtil(null,token).freeJwt();
    					if(freeJwt) {
    						//为了防止cookie被劫持、有效时间被篡改,对比一下redis
    						
    						//有效返回新的token  更新cookie、redis  cookie存的tokenId、redis存的tokenId、user
        					//Jedis jedis = JedisUtil.getJedis();
        					//String string = jedis.get(token);
//        					
        					Cookie cookie1 = new Cookie("tokenId", token);//将登录信息加入cookie中
        		            cookie1.setMaxAge(10*6); //设置cookie最大失效时间 10S             
        		            response.addCookie(cookie1);//将cookie返回加入
        					
        					return true;
    					}
    					
    				}
    				
    			 }
    		}
            //跳转到登录页
            String url = "/login";
            response.sendRedirect(url);
            return false;
        }
    }
 
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值