使用geteway网关中的GlobalFilter过滤器进行token验证

时间:2025-03-19 11:19:45

GlobalFilter过滤器进行token验证

    • GlobalFilter过滤器代码部分
  • JwtFactory和redis的MAVEN依赖
    • JwtFactory生成token(身份令牌):代码部分
    • 工具类代码:
    • token认证认证部分代码:

GlobalFilter过滤器代码部分

import ;
import ;
import ;
import ;
import ;
import .;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;

import ;

@Configuration
public class IsLoginGateway implements GlobalFilter,Ordered {

    @Autowired
    private TokenCacheUtil tokenCacheUtil;

    @Override
    public int getOrder() {
        return 1;
    }

	//拉取token过期时间
    @Value("${:43200000}")
    @RefreshScope
    public void setExpire(Long expire) {
        if (expire != null) {
            JwtConstant.JWT_REFRESH_TTL = (expire);
        }
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = ();
        ServerHttpResponse response = ();

        String userId = getLoginUserId(exchange);
        if (().name().equalsIgnoreCase("OPTIONS")) {
            JSONObject message = new JSONObject();
            ("statusCode", -1);
            ("msg", "请求类型错误!!!");
            byte[] bits = ().getBytes(StandardCharsets.UTF_8);
            DataBuffer buffer = ().wrap(bits);
            ();
            //指定编码,否则在浏览器中会中文乱码
            ().add("Content-Type", "text/plain;charset=UTF-8");
            return ((buffer));
        }
        if ((userId)) {
            ().getHeaders().set("isLogin", userId);
        } else {
            ().getHeaders().set("isLogin", "-1");
            JSONObject message = new JSONObject();
            ("statusCode", -1);
            ("msg", "鉴权失败");
            byte[] bits = ().getBytes(StandardCharsets.UTF_8);
            DataBuffer buffer = ().wrap(bits);
            ();
            //指定编码,否则在浏览器中会中文乱码
            ().add("Content-Type", "text/plain;charset=UTF-8");
            return ((buffer));
        }
        return (exchange);
    }

    private String getLoginUserId(ServerWebExchange exchange) {
        String userId = null;
        String auth =().getHeaders().getFirst("Authorization");

        if ((auth != null) && (() > 7)) {
            Claims claims = (auth);
            if (claims != null) {
                userId = ("userid") == null ? "" : ("userid").toString();
                if (!(auth, (userId))) {
                    return null;
                }
               ().put("userid",userId);
            }
        }
        return userId;
    }

}

JwtFactory和redis的MAVEN依赖

 <!--- 增加JwtFactory生成token(身份令牌)的依赖支持 -->
		<dependency>
            <groupId></groupId>
            <artifactId>jjwt</artifactId>
            <version>0.7.0</version>
        </dependency>

        <!--- 增加Redis支持 -->
        <dependency>
            <groupId></groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
            <version>1.5.</version>
        </dependency>

JwtFactory生成token(身份令牌):代码部分

import .Base64;
import ;
import ;
import ;
import ;

import ;
import ;
import ;

/**
 * Description:
 * Created with edanelx.
 * Create in: 2018/3/29 07:20
 */
public class JwtFactory {
    public JwtFactory() {
    }

    private static SecretKey generalKey() {
        String stringKey = "Mpk4ZjZim2Q0Nj0xZDMpM2NhZlU0ZTgzMrYyN2IpZjY";
        byte[] encodedKey = (()).getBytes();
        SecretKey key = new SecretKeySpec(encodedKey, 0, , "AES");
        return key;
    }

    public static Claims parseJWT(String jsonWebToken) {
        try {
            SecretKey key = generalKey();
            Claims claims = (Claims) ().setSigningKey(key).parseClaimsJws(jsonWebToken).getBody();
            return claims;
        } catch (Exception var3) {
            return null;
        }
    }

    public static String createJWT(String name, String userId) {
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
        long nowMillis = ();
        Date now = new Date(nowMillis);
        SecretKey signingKey = generalKey();
        JwtBuilder builder = ().setHeaderParam("typ", "JWT").claim("unique_name", name).claim("userid", userId).setIssuer("").setAudience("098f6bcd4621d373cade4e832627b4f6").setIssuedAt(now).signWith(signatureAlgorithm, signingKey);
        if (JwtConstant.JWT_REFRESH_TTL >= 0L) {
            long expMillis = nowMillis + JwtConstant.JWT_REFRESH_TTL;
            Date exp = new Date(expMillis);
            (exp).setNotBefore(now);
        }

        return ();
    }
}

工具类代码:

public class JwtConstant
 {
   public static final String JWT_ID = "098f6bcd4621d373cade4e832627b4f6";

   public static final String JWT_NAME = "";

   public static final String JWT_SECRET = "Mpk4ZjZim2Q0Nj0xZDMpM2NhZlU0ZTgzMrYyN2IpZjY";

   public static final int JWT_TTL = 3600000;

   public static final int JWT_REFRESH_INTERVAL = 3300000;
/* 15 */   public static long JWT_REFRESH_TTL = 3600000L;
 }


public class Constants {
    /*
     * token Key
     */
    public static final String TOKEN_KEY_PERFIX = "AUTH_TOKEN_";

    /**
     * 拦截器返回值:token错误
     */
    public static final int ERROR_RESPONSE_TOKEN_CODE = 1000;
    public static final String ERROR_RESPONSE_AUTH_TOKEN_TIMEOUT = "token过期,请重新登录";
    public static final String ERROR_RESPONSE_AUTH_PARSE = "无效的token";

}

token认证认证部分代码:

import ;
import ;
import ;

import ;

@Repository
public class TokenCacheUtil {

    @Autowired
    private StringRedisTemplate redisTemplate;

    /*@Value("${debug}")
    private boolean debug;*/

    private static final String CACHE_KEY_PREFIX = "user:token:pc:";

    private static final Integer[] BOSS_UID = new Integer[]{
            271498,
            427928,
            41458,
            246527,
            427190,
            393068,
            309,
            427837,
            427076,
            425074,
            710274,
            1066,
            832086,
            832082,
            832079,
            832081,
            832084,
            832078,
            832083,
            832080,
            832087,
            832092,
            832091,
            832094,
            832085,
            832265,
            832089,
            708432,
            708910,
            1000735,
            800361,
            1381946,
            1383092
    };

    private String getCacheKeyByUserId(Integer userId) {
        return CACHE_KEY_PREFIX + ();
    }

    public void saveToken(String token, Integer userId) {
        ().set(getCacheKeyByUserId(userId), token);
//        
        (getCacheKeyByUserId(userId), new Long(JwtConstant.JWT_REFRESH_TTL / 1000),);
    }

    public boolean checkTokenExists(String token, Integer userId) {
        for (Integer uid : BOSS_UID) {
            if ((userId)) {
                return true;
            }
        }
        
        String redisToken = ().get(getCacheKeyByUserId(userId));
        return redisToken != null && (token);
    }
}