上一章我们讲了用户登录开发,我们是基于redis管理token。这一章我们自定义过滤器实现权限校验,在项目中使用的是webflux不是springmvc。基于webflux自定义过滤器,通过实现WebFilter。
1.自定义过滤器
因为项目使用的是webFlux,自定义过滤器主要是实现WebFilter重写filter方法。过滤器内容主要包含①:不拦截的路径直接放过;②:校验token;③:登出接口处理,删除token;④:用户权限校验,判断是否有访问权限;⑤:token续期和向heard头添加userId和userName。
首先创建一个AdminLoginWebFilter类去实现WebFilter类并且重写filter方法,使用@Order注解来定义执行的顺序:
package com.hy.server.filter;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.fasterxml.jackson.core.type.TypeReference;
import com.hy.common.utils.JackJsonUtil;
import com.hy.common.utils.RedisCacheUtil;
import com.hy.common.utils.ServerWebExchangeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;
import reactor.core.publisher.Mono;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import static com.hy.common.constant.CommonConst.*;
import static com.hy.common.constant.CommonConst.NotInterceptUrl.ADMIN_USER_LOGIN_OUT;
import static com.hy.common.result.ResultCode.PATH_CANNOT_VISIT;
import static com.hy.common.result.ResultCode.TOKEN_NOT_VALID;
/**
* @ClassName: AdminLoginWebFilter
* @Description:
* @Author: songWenHao
* @Date: 2022/6/24 10:10
*/
@Slf4j
@Component
@Order(1)
public class AdminLoginWebFilter implements WebFilter {
@Override
public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
}
}
不做拦截的路径直接放过处理
package com.hy.server.filter;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.fasterxml.jackson.core.type.TypeReference;
import com.hy.common.utils.JackJsonUtil;
import com.hy.common.utils.RedisCacheUtil;
import com.hy.common.utils.ServerWebExchangeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;
import reactor.core.publisher.Mono;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import static com.hy.common.constant.CommonConst.*;
import static com.hy.common.constant.CommonConst.NotInterceptUrl.ADMIN_USER_LOGIN_OUT;
import static com.hy.common.result.ResultCode.PATH_CANNOT_VISIT;
import static com.hy.common.result.ResultCode.TOKEN_NOT_VALID;
/**
* @ClassName: AdminLoginWebFilter
* @Description:
* @Author: songWenHao
* @Date: 2022/6/24 10:10
*/
@Slf4j
@Component
@Order(1)
public class AdminLoginWebFilter implements WebFilter {
@Autowired
private RedisCacheUtil redisCacheUtil;
private static final PathMatcher matcher = new AntPathMatcher();
@Override
public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
ServerHttpRequest request = exchange.getRequest();
String requestPath = StrUtil.split(request.getPath().pathWithinApplication().value(), "?")[0];
// 不做拦截的路径
List<String> strings = CollUtil.toList(NOT_INTERCEPT_URL);
for (String noInterceptUrl : strings) {
if (matcher.match(noInterceptUrl, requestPath)) {
LOGGER.debug("不做拦截的URL: {}", noInterceptUrl);
return chain.filter(exchange);
}
}
}
}
校验token:token为空或者token失效
package com.hy.server.filter;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.fasterxml.jackson.core.type.TypeReference;
import com.hy.common.utils.JackJsonUtil;
import com.hy.common.utils.RedisCacheUtil;
import com.hy.common.utils.ServerWebExchangeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;
import reactor.core.publisher.Mono;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import static com.hy.common.constant.CommonConst.*;
import static com.hy.common.constant.CommonConst.NotInterceptUrl.ADMIN_USER_LOGIN_OUT;
import static com.hy.common.result.ResultCode.PATH_CANNOT_VISIT;
import static com.hy.common.result.ResultCode.TOKEN_NOT_VALID;
/**
* @ClassName: AdminLoginWebFilter
* @Description:
* @Author: songWenHao
* @Date: 2022/6/24 10:10
*/
@Slf4j
@Component
@Order(1)
public class AdminLoginWebFilter implements WebFilter {
@Autowired
private RedisCacheUtil redisCacheUtil;
private static final PathMatcher matcher = new AntPathMatcher();
@Override
public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
ServerHttpRequest request = exchange.getRequest();
String requestPath = StrUtil.split(request.getPath().pathWithinApplication().value(), "?")[0];
// 不做拦截的路径
List<String> strings = CollUtil.toList(NOT_INTERCEPT_URL);
for (String noInterceptUrl : strings) {
if (matcher.match(noInterceptUrl, requestPath)) {
LOGGER.debug("不做拦截的URL: {}", noInterceptUrl);
return chain.filter(exchange);
}
}
String token = request.getHeaders().getFirst(UAV_FINE_INSPECT_TOKEN);
if (StrUtil.isBlank(token)) {
LOGGER.info("无token信息");
return ServerWebExchangeUtils.handleForbidden(exchange.getResponse(), TOKEN_NOT_VALID);
}
Map<String, String> loginMap = redisCacheUtil.hashEntries(token);
if (CollUtil.isEmpty(loginMap) || StrUtil.equals("false", loginMap.get(LOGIN_STATUS))) {
LOGGER.info("token失效或未登录: {}", token);
return ServerWebExchangeUtils.handleForbidden(exchange.getResponse(), TOKEN_NOT_VALID);
}
}
}
登出接口处理:删除token
package com.hy.server.filter;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.fasterxml.jackson.core.type.TypeReference;
import com.hy.common.utils.JackJsonUtil;
import com.hy.common.utils.RedisCacheUtil;
import com.hy.common.utils.ServerWebExchangeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;
import reactor.core.publisher.Mono;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import static com.hy.common.constant.CommonConst.*;
import static com.hy.common.constant.CommonConst.NotInterceptUrl.ADMIN_USER_LOGIN_OUT;
import static com.hy.common.result.ResultCode.PATH_CANNOT_VISIT;
import static com.hy.common.result.ResultCode.TOKEN_NOT_VALID;
/**
* @ClassName: AdminLoginWebFilter
* @Description:
* @Author: songWenHao
* @Date: 2022/6/24 10:10
*/
@Slf4j
@Component
@Order(1)
public class AdminLoginWebFilter implements WebFilter {
@Autowired
private RedisCacheUtil redisCacheUtil;
private static final PathMatcher matcher = new AntPathMatcher();
@Override
public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
ServerHttpRequest request = exchange.getRequest();
String requestPath = StrUtil.split(request.getPath().pathWithinApplication().value(), "?")[0];
// 不做拦截的路径
List<String> strings = CollUtil.toList(NOT_INTERCEPT_URL);
for (String noInterceptUrl : strings) {
if (matcher.match(noInterceptUrl, requestPath)) {
LOGGER.debug("不做拦截的URL: {}", noInterceptUrl);
return chain.filter(exchange);
}
}
String token = request.getHeaders().getFirst(UAV_FINE_INSPECT_TOKEN);
if (StrUtil.isBlank(token)) {
LOGGER.info("无token信息");
return ServerWebExchangeUtils.handleForbidden(exchange.getResponse(), TOKEN_NOT_VALID);
}
Map<String, String> loginMap = redisCacheUtil.hashEntries(token);
if (CollUtil.isEmpty(loginMap) || StrUtil.equals("false", loginMap.get(LOGIN_STATUS))) {
LOGGER.info("token失效或未登录: {}", token);
return ServerWebExchangeUtils.handleForbidden(exchange.getResponse(), TOKEN_NOT_VALID);
}
//如果是登出接口,删除token
if (matcher.match(ADMIN_USER_LOGIN_OUT, requestPath)) {
LOGGER.debug("管理员登出接口: {}", ADMIN_USER_LOGIN_OUT);
redisCacheUtil.stringDel(token);
return ServerWebExchangeUtils.handleOk(exchange.getResponse());
}
}
}
校验用户是否有访问该路径的权限
package com.hy.server.filter;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.fasterxml.jackson.core.type.TypeReference;
import com.hy.common.utils.JackJsonUtil;
import com.hy.common.utils.RedisCacheUtil;
import com.hy.common.utils.ServerWebExchangeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;
import reactor.core.publisher.Mono;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import static com.hy.common.constant.CommonConst.*;
import static com.hy.common.constant.CommonConst.NotInterceptUrl.ADMIN_USER_LOGIN_OUT;
import static com.hy.common.result.ResultCode.PATH_CANNOT_VISIT;
import static com.hy.common.result.ResultCode.TOKEN_NOT_VALID;
/**
* @ClassName: AdminLoginWebFilter
* @Description:
* @Author: songWenHao
* @Date: 2022/6/24 10:10
*/
@Slf4j
@Component
@Order(1)
public class AdminLoginWebFilter implements WebFilter {
@Autowired
private RedisCacheUtil redisCacheUtil;
private static final PathMatcher matcher = new AntPathMatcher();
@Override
public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
ServerHttpRequest request = exchange.getRequest();
String requestPath = StrUtil.split(request.getPath().pathWithinApplication().value(), "?")[0];
// 不做拦截的路径
List<String> strings = CollUtil.toList(NOT_INTERCEPT_URL);
for (String noInterceptUrl : strings) {
if (matcher.match(noInterceptUrl, requestPath)) {
LOGGER.debug("不做拦截的URL: {}", noInterceptUrl);
return chain.filter(exchange);
}
}
String token = request.getHeaders().getFirst(UAV_FINE_INSPECT_TOKEN);
if (StrUtil.isBlank(token)) {
LOGGER.info("无token信息");
return ServerWebExchangeUtils.handleForbidden(exchange.getResponse(), TOKEN_NOT_VALID);
}
Map<String, String> loginMap = redisCacheUtil.hashEntries(token);
if (CollUtil.isEmpty(loginMap) || StrUtil.equals("false", loginMap.get(LOGIN_STATUS))) {
LOGGER.info("token失效或未登录: {}", token);
return ServerWebExchangeUtils.handleForbidden(exchange.getResponse(), TOKEN_NOT_VALID);
}
//如果是登出接口,删除token
if (matcher.match(ADMIN_USER_LOGIN_OUT, requestPath)) {
LOGGER.debug("管理员登出接口: {}", ADMIN_USER_LOGIN_OUT);
redisCacheUtil.stringDel(token);
return ServerWebExchangeUtils.handleOk(exchange.getResponse());
}
String resPaths = loginMap.get(ADMIN_RES_PATH);
if (StrUtil.isBlank(resPaths)) {
LOGGER.debug("无path路径信息,token无法访问: {}", token);
return ServerWebExchangeUtils.handleForbidden(exchange.getResponse(), PATH_CANNOT_VISIT);
}
List<String> resList = JackJsonUtil.string2Obj(resPaths, new TypeReference<List<String>>() {
});
boolean pathCanVisit = false;
for (String path : resList) {
String tmpRequestPath = requestPath;
int index = StrUtil.indexOf(path, '{');
if (index > 0) {
//路径带参数 取 ‘{’ 之前的路径
//根据路径中参数之前的长度 截取url路径 做比较
tmpRequestPath = StrUtil.subPre(requestPath, index);
path = StrUtil.subPre(path, index);
}
if (matcher.match(path, tmpRequestPath)) {
pathCanVisit = true;
break;
}
}
if (!pathCanVisit) {
LOGGER.debug("当前路径无访问权限: {}", requestPath);
return ServerWebExchangeUtils.handleForbidden(exchange.getResponse(), PATH_CANNOT_VISIT);
}
}
}
token续期和向heard头里添加userId和userName
package com.hy.server.filter;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.fasterxml.jackson.core.type.TypeReference;
import com.hy.common.utils.JackJsonUtil;
import com.hy.common.utils.RedisCacheUtil;
import com.hy.common.utils.ServerWebExchangeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;
import reactor.core.publisher.Mono;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import static com.hy.common.constant.CommonConst.*;
import static com.hy.common.constant.CommonConst.NotInterceptUrl.ADMIN_USER_LOGIN_OUT;
import static com.hy.common.result.ResultCode.PATH_CANNOT_VISIT;
import static com.hy.common.result.ResultCode.TOKEN_NOT_VALID;
/**
* @ClassName: AdminLoginWebFilter
* @Description:
* @Author: songWenHao
* @Date: 2022/6/24 10:10
*/
@Slf4j
@Component
@Order(1)
public class AdminLoginWebFilter implements WebFilter {
@Autowired
private RedisCacheUtil redisCacheUtil;
private static final PathMatcher matcher = new AntPathMatcher();
@Override
public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
ServerHttpRequest request = exchange.getRequest();
String requestPath = StrUtil.split(request.getPath().pathWithinApplication().value(), "?")[0];
// 不做拦截的路径
List<String> strings = CollUtil.toList(NOT_INTERCEPT_URL);
for (String noInterceptUrl : strings) {
if (matcher.match(noInterceptUrl, requestPath)) {
LOGGER.debug("不做拦截的URL: {}", noInterceptUrl);
return chain.filter(exchange);
}
}
String token = request.getHeaders().getFirst(UAV_FINE_INSPECT_TOKEN);
if (StrUtil.isBlank(token)) {
LOGGER.info("无token信息");
return ServerWebExchangeUtils.handleForbidden(exchange.getResponse(), TOKEN_NOT_VALID);
}
Map<String, String> loginMap = redisCacheUtil.hashEntries(token);
if (CollUtil.isEmpty(loginMap) || StrUtil.equals("false", loginMap.get(LOGIN_STATUS))) {
LOGGER.info("token失效或未登录: {}", token);
return ServerWebExchangeUtils.handleForbidden(exchange.getResponse(), TOKEN_NOT_VALID);
}
//如果是登出接口,删除token
if (matcher.match(ADMIN_USER_LOGIN_OUT, requestPath)) {
LOGGER.debug("管理员登出接口: {}", ADMIN_USER_LOGIN_OUT);
redisCacheUtil.stringDel(token);
return ServerWebExchangeUtils.handleOk(exchange.getResponse());
}
String resPaths = loginMap.get(ADMIN_RES_PATH);
if (StrUtil.isBlank(resPaths)) {
LOGGER.debug("无path路径信息,token无法访问: {}", token);
return ServerWebExchangeUtils.handleForbidden(exchange.getResponse(), PATH_CANNOT_VISIT);
}
List<String> resList = JackJsonUtil.string2Obj(resPaths, new TypeReference<List<String>>() {
});
boolean pathCanVisit = false;
for (String path : resList) {
String tmpRequestPath = requestPath;
int index = StrUtil.indexOf(path, '{');
if (index > 0) {
//路径带参数 取 ‘{’ 之前的路径
//根据路径中参数之前的长度 截取url路径 做比较
tmpRequestPath = StrUtil.subPre(requestPath, index);
path = StrUtil.subPre(path, index);
}
if (matcher.match(path, tmpRequestPath)) {
pathCanVisit = true;
break;
}
}
if (!pathCanVisit) {
LOGGER.debug("当前路径无访问权限: {}", requestPath);
return ServerWebExchangeUtils.handleForbidden(exchange.getResponse(), PATH_CANNOT_VISIT);
}
// token续期
redisCacheUtil.setExpire(token, SESSION_TIME, TimeUnit.MINUTES);
HttpHeaders headersTmp = new HttpHeaders();
headersTmp.add(ADMIN_USER_NAME, loginMap.get(ADMIN_USER_NAME));
headersTmp.add(ADMIN_USER_ID, loginMap.get(ADMIN_USER_ID));
return chain.filter(exchange.mutate().request(request.mutate().headers(httpHeaders -> httpHeaders.putAll(headersTmp)).build()).build());
}
}