| | |
| | | package com.ruoyi.gateway.filter; |
| | | |
| | | import java.util.Arrays; |
| | | import javax.annotation.Resource; |
| | | import org.slf4j.Logger; |
| | | import org.slf4j.LoggerFactory; |
| | | import org.springframework.beans.factory.annotation.Autowired; |
| | | import org.springframework.cloud.gateway.filter.GatewayFilterChain; |
| | | import org.springframework.cloud.gateway.filter.GlobalFilter; |
| | | import org.springframework.core.Ordered; |
| | | import org.springframework.core.io.buffer.DataBufferFactory; |
| | | import org.springframework.data.redis.core.ValueOperations; |
| | | import org.springframework.http.HttpStatus; |
| | | import org.springframework.http.MediaType; |
| | | import org.springframework.http.server.reactive.ServerHttpRequest; |
| | | import org.springframework.http.server.reactive.ServerHttpResponse; |
| | | import org.springframework.stereotype.Component; |
| | | import org.springframework.web.server.ServerWebExchange; |
| | | import com.alibaba.fastjson.JSON; |
| | | import com.alibaba.fastjson.JSONObject; |
| | | import com.ruoyi.common.core.constant.CacheConstants; |
| | | import com.ruoyi.common.core.domain.R; |
| | | import com.ruoyi.common.core.constant.HttpStatus; |
| | | import com.ruoyi.common.core.constant.SecurityConstants; |
| | | import com.ruoyi.common.core.constant.TokenConstants; |
| | | import com.ruoyi.common.core.utils.JwtUtils; |
| | | import com.ruoyi.common.core.utils.ServletUtils; |
| | | import com.ruoyi.common.core.utils.StringUtils; |
| | | import com.ruoyi.common.redis.service.RedisService; |
| | | import com.ruoyi.gateway.config.properties.IgnoreWhiteProperties; |
| | | import io.jsonwebtoken.Claims; |
| | | import reactor.core.publisher.Mono; |
| | | |
| | | /** |
| | |
| | | { |
| | | private static final Logger log = LoggerFactory.getLogger(AuthFilter.class); |
| | | |
| | | // 排除过滤的 uri 地址,swagger排除自行添加 |
| | | private static final String[] whiteList = { "/auth/login", "/code/v2/api-docs", "/schedule/v2/api-docs", |
| | | "/system/v2/api-docs", "/csrf" }; |
| | | // 排除过滤的 uri 地址,nacos自行添加 |
| | | @Autowired |
| | | private IgnoreWhiteProperties ignoreWhite; |
| | | |
| | | @Resource(name = "stringRedisTemplate") |
| | | private ValueOperations<String, String> sops; |
| | | @Autowired |
| | | private RedisService redisService; |
| | | |
| | | |
| | | @Override |
| | | public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) |
| | | { |
| | | String url = exchange.getRequest().getURI().getPath(); |
| | | ServerHttpRequest request = exchange.getRequest(); |
| | | ServerHttpRequest.Builder mutate = request.mutate(); |
| | | |
| | | String url = request.getURI().getPath(); |
| | | // 跳过不需要验证的路径 |
| | | if (Arrays.asList(whiteList).contains(url)) |
| | | if (StringUtils.matches(url, ignoreWhite.getWhites())) |
| | | { |
| | | return chain.filter(exchange); |
| | | } |
| | | String token = getToken(exchange.getRequest()); |
| | | if (StringUtils.isBlank(token)) |
| | | String token = getToken(request); |
| | | if (StringUtils.isEmpty(token)) |
| | | { |
| | | return setUnauthorizedResponse(exchange, "令牌不能为空"); |
| | | return unauthorizedResponse(exchange, "令牌不能为空"); |
| | | } |
| | | String userStr = sops.get(CacheConstants.LOGIN_TOKEN_KEY + token); |
| | | if (StringUtils.isNull(userStr)) |
| | | Claims claims = JwtUtils.parseToken(token); |
| | | if (claims == null) |
| | | { |
| | | return setUnauthorizedResponse(exchange, "令牌验证失败"); |
| | | return unauthorizedResponse(exchange, "令牌已过期或验证不正确!"); |
| | | } |
| | | JSONObject obj = JSONObject.parseObject(userStr); |
| | | String userid = obj.getString("userid"); |
| | | String username = obj.getString("username"); |
| | | if (StringUtils.isBlank(userid) || StringUtils.isBlank(username)) |
| | | String userkey = JwtUtils.getUserKey(claims); |
| | | boolean islogin = redisService.hasKey(getTokenKey(userkey)); |
| | | if (!islogin) |
| | | { |
| | | return setUnauthorizedResponse(exchange, "令牌验证失败"); |
| | | return unauthorizedResponse(exchange, "登录状态已过期"); |
| | | } |
| | | String userid = JwtUtils.getUserId(claims); |
| | | String username = JwtUtils.getUserName(claims); |
| | | if (StringUtils.isEmpty(userid) || StringUtils.isEmpty(username)) |
| | | { |
| | | return unauthorizedResponse(exchange, "令牌验证失败"); |
| | | } |
| | | |
| | | // 设置用户信息到请求 |
| | | ServerHttpRequest mutableReq = exchange.getRequest().mutate().header(CacheConstants.DETAILS_USER_ID, userid) |
| | | .header(CacheConstants.DETAILS_USERNAME, username).build(); |
| | | ServerWebExchange mutableExchange = exchange.mutate().request(mutableReq).build(); |
| | | |
| | | return chain.filter(mutableExchange); |
| | | addHeader(mutate, SecurityConstants.USER_KEY, userkey); |
| | | addHeader(mutate, SecurityConstants.DETAILS_USER_ID, userid); |
| | | addHeader(mutate, SecurityConstants.DETAILS_USERNAME, username); |
| | | // 内部请求来源参数清除 |
| | | removeHeader(mutate, SecurityConstants.FROM_SOURCE); |
| | | return chain.filter(exchange.mutate().request(mutate.build()).build()); |
| | | } |
| | | |
| | | private Mono<Void> setUnauthorizedResponse(ServerWebExchange exchange, String msg) |
| | | private void addHeader(ServerHttpRequest.Builder mutate, String name, Object value) |
| | | { |
| | | ServerHttpResponse response = exchange.getResponse(); |
| | | response.getHeaders().setContentType(MediaType.APPLICATION_JSON); |
| | | response.setStatusCode(HttpStatus.OK); |
| | | if (value == null) |
| | | { |
| | | return; |
| | | } |
| | | String valueStr = value.toString(); |
| | | String valueEncode = ServletUtils.urlEncode(valueStr); |
| | | mutate.header(name, valueEncode); |
| | | } |
| | | |
| | | private void removeHeader(ServerHttpRequest.Builder mutate, String name) |
| | | { |
| | | mutate.headers(httpHeaders -> httpHeaders.remove(name)).build(); |
| | | } |
| | | |
| | | private Mono<Void> unauthorizedResponse(ServerWebExchange exchange, String msg) |
| | | { |
| | | log.error("[鉴权异常处理]请求路径:{}", exchange.getRequest().getPath()); |
| | | return ServletUtils.webFluxResponseWriter(exchange.getResponse(), msg, HttpStatus.UNAUTHORIZED); |
| | | } |
| | | |
| | | return response.writeWith(Mono.fromSupplier(() -> { |
| | | DataBufferFactory bufferFactory = response.bufferFactory(); |
| | | return bufferFactory.wrap(JSON.toJSONBytes(R.fail(msg))); |
| | | })); |
| | | /** |
| | | * 获取缓存key |
| | | */ |
| | | private String getTokenKey(String token) |
| | | { |
| | | return CacheConstants.LOGIN_TOKEN_KEY + token; |
| | | } |
| | | |
| | | /** |
| | |
| | | */ |
| | | private String getToken(ServerHttpRequest request) |
| | | { |
| | | String token = request.getHeaders().getFirst(CacheConstants.HEADER); |
| | | if (StringUtils.isNotEmpty(token) && token.startsWith(CacheConstants.TOKEN_PREFIX)) |
| | | String token = request.getHeaders().getFirst(TokenConstants.AUTHENTICATION); |
| | | // 如果前端设置了令牌前缀,则裁剪掉前缀 |
| | | if (StringUtils.isNotEmpty(token) && token.startsWith(TokenConstants.PREFIX)) |
| | | { |
| | | token = token.replace(CacheConstants.TOKEN_PREFIX, ""); |
| | | token = token.replaceFirst(TokenConstants.PREFIX, StringUtils.EMPTY); |
| | | } |
| | | return token; |
| | | } |