1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
| package com.qingchen.filter;
import com.alibaba.cloud.commons.lang.StringUtils; import com.qingchen.base.BaseInfoProperties; import com.qingchen.grace.result.ResponseStatusEnum; import jakarta.annotation.Resource; import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.context.config.annotation.RefreshScope; import org.springframework.cloud.gateway.filter.GatewayFilterChain; import org.springframework.cloud.gateway.filter.GlobalFilter; import org.springframework.core.Ordered; import org.springframework.http.HttpHeaders; import org.springframework.stereotype.Component; import org.springframework.util.AntPathMatcher; import org.springframework.web.server.ServerWebExchange; import reactor.core.publisher.Mono;
import java.util.List;
@Component @Slf4j @RefreshScope public class SecurityFilterToken extends BaseInfoProperties implements GlobalFilter, Ordered { @Resource private ExcludeUrlProperties excludeUrlProperties; private AntPathMatcher antPathMatcher=new AntPathMatcher(); @Override public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) { String url=exchange.getRequest().getURI().getPath(); log.info("SecurityFilterToken url={}",url); List<String> excludeList=excludeUrlProperties.getUrls(); if(excludeList!=null&&!excludeList.isEmpty()){ for(String excludeUrl:excludeList){ if(antPathMatcher.matchStart(excludeUrl,url)){ return chain.filter(exchange); } } } String fileStart = excludeUrlProperties.getFileStart(); if(StringUtils.isNotBlank(fileStart)){ boolean matchFileStart=antPathMatcher.matchStart(fileStart,url); if(matchFileStart){ return chain.filter(exchange); } } log.info("当前请求路径[{}]被拦截...",url); HttpHeaders headers=exchange.getRequest().getHeaders(); String userId=headers.getFirst(HEADER_USER_ID); String userToken=headers.getFirst(HEADER_USER_TOKEN); log.info("userId={}",userId); log.info("userToken={}",userToken); if(StringUtils.isNotBlank(userId)&&StringUtils.isNotBlank(userToken)){ log.info("userId与userToken都不为空"); String redisToken=redis.get(REDIS_USER_TOKEN+":"+userId); if(redisToken.equalsIgnoreCase(userToken)){ log.info("放行成功"); return chain.filter(exchange); } }
return RenderErrorUtils.display(exchange, ResponseStatusEnum.UN_LOGIN); }
@Override public int getOrder() { return 0; } }
|