当前位置:网站首页>中小型项目手撸过滤器实现认证与授权
中小型项目手撸过滤器实现认证与授权
2022-07-02 05:24:00 【泊船夜雪,他年可期】
中小型项目手撸过滤器实现认证与授权
代码实现
@Component
@WebFilter(urlPatterns = "/*", filterName = "tokenFilter")
public class TokenFilter implements Filter {
// token 过期时间
@Value("${token-expired-time}")
private int tokenExpiredTime;
// uri 请求白名单
@Resource
private WhiteListConfig whiteListConfig;
@Resource
private RedisTemplate<String, Object> redisTemplate;
// 进行异常处理
@Resource
@Qualifier("handlerExceptionResolver")
private HandlerExceptionResolver resolver;
@Override
public void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws IOException, ServletException {
// 请求头里的 token 值,这里需要注意自己项目里 token 对应的 key 是什么
// 我这里是 public static final String AUTH_TOKEN = "auth-token";
String authToken = request.getHeader(Constants.AUTH_TOKEN);
// 请求地址
String requestURI = request.getRequestURI();
// 校验白名单里是否包含当前 uri
boolean flag = whiteListConfig.getNotCheck().stream().anyMatch(u -> requestURI.equals("/"+u));
// 通过校验
if (flag) {
// 则通过认证,进行放行
filterChain.doFilter(request, response);
} else if (StringUtils.isNotBlank(authToken) && redisTemplate.hasKey(authToken)) {
// 非白名单,需要 token 认证
// 进行授权
// redis 里面存储了该用户的权限信息集合,如:角色、菜单、功能等权限信息
TokenInfo tokenInfo = (TokenInfo) redisTemplate.opsForValue().get(authToken);
assert tokenInfo != null;
boolean empower = tokenInfo.getEmpowers() != null && tokenInfo.getEmpowers().size() > 0 && tokenInfo.getEmpowers().stream().anyMatch((requestURI)::equals);
// 认证并授权则通过
if (empower){
// 刷新 token 的过期时间
redisTemplate.expire(token,tokenOvertime,TimeUnit.SECONDS);
filterChain.doFilter(request, response);
}else {
// 如果已认证但无授权信息
resolver.resolveException(request, response, null,new Err(Status.ILLEGAL_REQUEST.getStatus(),Status.ILLEGAL_REQUEST.getError()));
}
} else {
// 没有匹配到 redis 里面的 key,key 就是 authToken;这些请求业务中是直接拒绝请求并抛出异常,记录相关信息
resolver.resolveException(request, response, null, StringUtils.isBlank(authToken) ? new Err("请求头中的 auth-token 信息不能为空!") : new Err(Status.NOT_LOGIN.getStatus(), Status.NOT_LOGIN.getError()));
}
}
}
总结
总体思路大致如上,细节上可根据项目信息具体进行变更。
边栏推荐
- JVM class loading mechanism
- Reflection of the soul of the frame (important knowledge)
- Principle and implementation of parallax effect
- Gee: analyze the change of spatial centroid of remote sensing image [centroid acquisition analysis]
- Collectors.groupingBy 排序
- LeetCode 1175. 质数排列(质数判断+组合数学)
- Draw a wave chart_ Digital IC
- 【技术随记-08】
- Fabric.js 3个api设置画布宽高
- Pycharm breakpoint management: temporarily cancel some breakpoints + run directly to a line
猜你喜欢

LS1046nfs挂载文件系统

Fabric. JS upload local image to canvas background

摆正元素(带过渡动画)

Fabric. JS iText set italics manually

指针使用详解

Collectors. Groupingby sort

Principle and implementation of parallax effect

Fabric. JS iText sets the color and background color of the specified text

6.网络-基础

Disable access to external entities in XML parsing
随机推荐
Fabric.js 自由绘制矩形
运维工作的“本手、妙手、俗手”
Fabric. JS iText superscript and subscript
[opencv] image binarization
在{{}}中拼接字符
leetcode存在重复元素go实现
Disable access to external entities in XML parsing
Fabric. JS free draw rectangle
【pyinstaller】_ get_ sysconfigdata_ name() missing 1 required positional argument: ‘check_ exists‘
Disable access to external entities in XML parsing
线程池批量处理数据
Fabric.js 右键菜单
brew install * 失败,解决方法
简单封装 js并应用
Global and Chinese markets of semiconductor laser therapeutics 2022-2028: Research Report on technology, participants, trends, market size and share
6. Network - Foundation
Gee series: unit 6 building various remote sensing indexes in Google Earth engine
Gee series: Unit 1 Introduction to Google Earth engine
Nodejs (03) -- custom module
数据的储存