当前位置: 首页 > news >正文

自定义SpringMVC拦截器,实现内外网访问控制功能

这篇文章简单介绍如何自定义一个SpringMVC拦截器,并通过拦截器实现具体的功能。

首先,需要创建一个自定义的拦截器类,该类实现HandlerInterceptor接口。

package cn.edu.sgu.www.mhxysy.interceptor;import cn.edu.sgu.www.mhxysy.feign.FeignService;
import cn.edu.sgu.www.mhxysy.property.NetworkProperties;
import cn.edu.sgu.www.mhxysy.restful.JsonResult;
import cn.edu.sgu.www.mhxysy.restful.ResponseCode;
import cn.edu.sgu.www.mhxysy.util.IpUtils;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashSet;
import java.util.List;
import java.util.Set;/*** 自定义拦截器* @author heyunlin* @version 1.0*/
@Slf4j
@Component
public class WebInterceptor implements HandlerInterceptor {@Value("${spring.application.name}")private final String service = "mhxysy";/*** 匿名接口权限*/private static Set<String> ANONYMITY_URLS;private final NetworkProperties networkProperties;@Autowiredpublic WebInterceptor(FeignService feignService, NetworkProperties networkProperties) {this.networkProperties = networkProperties;if (ANONYMITY_URLS == null) {List<String> permissions = feignService.selectAnonymityPermissions(service);ANONYMITY_URLS = new HashSet<>(permissions);}}@Overridepublic boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {// 获取请求urlString requestURI = request.getRequestURI();// 1、处理匿名访问接口,直接跳过鉴权if (ANONYMITY_URLS.contains(requestURI)) {log.debug("匿名接口" + requestURI + "正在被访问...");return true;}// 2、内外网控制if (networkProperties.isEnableInnerIpAccess()) {// 得到客户端IPString clientIp = IpUtils.getIp();if (!networkProperties.getInnerIps().contains(clientIp)) {// 构建返回对象JsonResult<Void> jsonResult = JsonResult.error(ResponseCode.FORBIDDEN, requestURI + "只允许内网访问~");// 设置内容类型为jsonresponse.setContentType("application/json;charset=utf-8");// 设置响应状态码response.setStatus(ResponseCode.FORBIDDEN.getValue());response.getWriter().write(JSON.toJSONString(jsonResult));return false;}}return true;}/*** 获取匿名接口列表* @return Set<String>*/public static Set<String> getAnonymityUrls() {return ANONYMITY_URLS;}}

IpUtils.java

package cn.edu.sgu.www.mhxysy.util;import javax.servlet.http.HttpServletRequest;/*** ip地址工具类* @author heyunlin* @version 1.0*/
public class IpUtils {/*** 获取客户端IP* @return String*/public static String getIp() {HttpServletRequest request = UserUtils.getRequest();String ip = request.getHeader("x-forwarded-for");if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {ip = request.getHeader("Proxy-Client-IP");}if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {ip = request.getHeader("WL-Proxy-Client-IP");}if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {ip = request.getHeader("HTTP_CLIENT_IP");}if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {ip = request.getHeader("HTTP_X_FORWARDED_FOR");}if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {ip = request.getHeader("X-Real-IP");}if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {ip = request.getRemoteAddr();}return ip;}/*** 获取浏览器类型* @return String 浏览器类型*/public static String getBrowserType() {HttpServletRequest request = UserUtils.getRequest();String type = "其它";String browserName = request.getHeader("USER-AGENT").toLowerCase();if (browserName.indexOf("msie") > 0) {type = "IE";} else if (browserName.indexOf("firefox") > 0) {type = "Firefox";} else if (browserName.indexOf("chrome") > 0) {type = "Chrome";} else if (browserName.indexOf("opera") > 0) {type = "Opera";} else if (browserName.indexOf("gecko") > 0 && browserName.indexOf("rv:11") > 0) {type = "IE11";}return type;}}

然后把拦截器注册到SpringMVC

package cn.edu.sgu.www.mhxysy.config;import cn.edu.sgu.www.mhxysy.interceptor.WebInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.servlet.ServletContextInitializer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;import javax.servlet.ServletContext;/*** springmvc配置类* @author heyunlin* @version 1.0*/
@Configuration
public class SpringMvcConfig implements WebMvcConfigurer {@Value("${uploads.path}")private String uploadPath;private final WebInterceptor webInterceptor;@Autowiredpublic SpringMvcConfig(WebInterceptor webInterceptor) {this.webInterceptor = webInterceptor;}/*** 解决跨域问题*/@Overridepublic void addCorsMappings(CorsRegistry registry) {registry.addMapping("/**").allowedOrigins("*").allowedMethods("*").allowedHeaders("*").allowCredentials(true).maxAge(5000);}/*** 添加静态资源路径*/@Overridepublic void addResourceHandlers(ResourceHandlerRegistry registry) {// 配置静态资源路径registry.addResourceHandler("/**").addResourceLocations("classpath:static/").addResourceLocations("file:" + uploadPath + "/");// 解决knife4j访问失败问题registry.addResourceHandler("doc.html").addResourceLocations("classpath:/META-INF/resources/");registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");}@Overridepublic void addInterceptors(InterceptorRegistry registry) {registry.addInterceptor(webInterceptor).addPathPatterns("/**");}/*** 设置SESSION_ID* @return ServletContextInitializer*/@Beanpublic ServletContextInitializer servletContextInitializer() {return new ServletContextInitializer() {@Overridepublic void onStartup(ServletContext servletContext) {servletContext.getSessionCookieConfig().setName("MHXYSY_JSESSIONID");}};}}

http://www.lryc.cn/news/217093.html

相关文章:

  • 在pycharm中配置GPU训练环境(Anaconda)(yolov5)
  • 【LeetCode刷题-链表】--146.LRU缓存
  • mysql 问题解答
  • 组件与Props:React中构建可复用UI的基石
  • 接口框架第二篇—unittest/pytest 有什么区别
  • Window 7 / 10 / 11 .bat .cmd 中文路径不识别解决方案
  • Linux命令(113)之rev
  • QT+SQLite数据库配置和使用
  • 若依分离版——配置多数据源(mysql和oracle),实现一个方法操作多个数据源
  • Seata入门系列【19】分布式事务之CAP、BASE理论
  • 界面控件DevExpress WPF Gauge组件 - 轻松实现个性化商业仪表盘
  • 算法题:870. 优势洗牌
  • [架构之路-252/创业之路-83]:目标系统 - 纵向分层 - 企业信息化的呈现形态:常见企业信息化软件系统 - 企业应用信息系统集成
  • MFC发送http https以及json解析
  • UE5加载websocket模块为空
  • 学习 Python 数据可视化,如何快速入门?
  • XUbuntu22.04之simplenote支持的Markdown语法总结(一百九十一)
  • JAVA深化篇_26——Apache commons-io工具包的使用
  • centos 7 kafka2.6单机安装及动态认证SASL SCRAM配置
  • TrafficWatch 数据包嗅探器工具
  • MySQL Binlog实战应用之一
  • 【MySQL】MVCC机制(undo log,read view)
  • gma 2 教程(三)坐标参考系统:3.投影方法
  • 蓝桥杯每日一题2023.11.2
  • Leetcode67二进制求和
  • 线性代数 第五章 特征值与特征向量
  • Python嵌入式数据库 / 轻量级数据库 / 小型数据库介绍(SQLite、Pandas DataFrame、TinyDB)(python数据库)
  • USB PD v1.0快速充电通信原理
  • 【华为】路由器以PPPoE拨号接入广域网
  • Linux内核分析(一)--内核架构和子系统