当前位置:网站首页>中小型项目手撸过滤器实现认证与授权
中小型项目手撸过滤器实现认证与授权
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()));
}
}
}
总结
总体思路大致如上,细节上可根据项目信息具体进行变更。
边栏推荐
- Fabric.js 右键菜单
- 操作符详解
- Global and Chinese market of impact roll 2022-2028: Research Report on technology, participants, trends, market size and share
- Splice characters in {{}}
- Fabric.js 更换图片的3种方法(包括更换分组内的图片,以及存在缓存的情况)
- 线程池批量处理数据
- Gee data set: export the distribution and installed capacity of hydropower stations in the country to CSV table
- How to make an RPM file
- Using QA band and bit mask in Google Earth engine
- Fabric. JS basic brush
猜你喜欢

LeetCode 1175. Prime number arrangement (prime number judgment + Combinatorial Mathematics)

7.TCP的十一种状态集

【pyinstaller】_ get_ sysconfigdata_ name() missing 1 required positional argument: ‘check_ exists‘

6. Network - Foundation
![Gee: use of common mask functions in remote sensing image processing [updatemask]](/img/55/bf4ef5fc923242e72caab71f1a4e4b.jpg)
Gee: use of common mask functions in remote sensing image processing [updatemask]

运维工作的“本手、妙手、俗手”

JVM class loading mechanism

Gee series: Unit 2 explore datasets

Pyechart1.19 national air quality exhibition

Gee series: Unit 4 data import and export in Google Earth engine
随机推荐
黑马笔记---Map集合体系
Fabric.js IText 上标和下标
php/js cookie共享跨域的问题
Thread pool batch processing data
生成二维码
Exercise notes 13 (effective letter ectopic words)
How matlab marks' a 'in the figure and how matlab marks points and solid points in the figure
Gee series: Unit 4 data import and export in Google Earth engine
创新永不止步——nVisual网络可视化平台针对Excel导入的创新历程
【pyinstaller】_ get_ sysconfigdata_ name() missing 1 required positional argument: ‘check_ exists‘
LeetCode 241. Design priorities for operational expressions (divide and conquer / mnemonic recursion / dynamic programming)
Global and Chinese markets of semiconductor laser therapeutics 2022-2028: Research Report on technology, participants, trends, market size and share
Nodejs (03) -- custom module
Black Horse Notes - - set Series Collection
Gee: remote sensing image composite and mosaic
Mysql基础---查询(1天学会mysql基础)
Fabric.js 将本地图像上传到画布背景
Fabric.js 圆形笔刷
画波形图_数字IC
Global and Chinese markets for marine selective catalytic reduction systems 2022-2028: Research Report on technology, participants, trends, market size and share