生成token和全局过滤器验证token

生成token

import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.security.Keys;

import javax.crypto.SecretKey;
import java.util.Date;
import java.util.Map;

public class JwtUtil {

    /**
     * 32字符 * 8bit = 256bit 
     * 自定义 Key,32位即可
     */
    public static final String KEY = "11111111111111111111111111111111";

    /**
     * 签名秘钥
     */
    private static SecretKey secretKey = Keys.hmacShaKeyFor(KEY.getBytes());

    /**
     * 12小时的毫秒数
     */
    private static final long EXPIRE = 1000 * 60 * 60 * 12;
		
	/**
     * 生成token
	 */
    public static String create(Map<String, Object> claimsMap) {
        Date now = new Date();
        //                            签名秘钥           自定义内容             发行时间                 过期时间
        return Jwts.builder().signWith(secretKey).setClaims(claimsMap).setIssuedAt(now).setExpiration(new Date(now.getTime() + EXPIRE)).compact();
    }
	
	/**
     * 解析请求头
	 */
    public static Map<String, Object> parse(String jwt) {
        return Jwts.parserBuilder().setSigningKey(secretKey).build().parseClaimsJws(jwt).getBody();
    }
}

token过滤器(全局)验证是否携带token

一定要记得设置优先级!!!如果没有实现Ordered接口进行排序的话,网关路由会先进行验证,对于一些不需要验证token的路由来说,会出现错误。
实现GlobalFilter接口,默认添加到所有的路由上

import cn.hutool.json.JSONUtil;
import com.user.common.core.properties.ImageProperties;
import com.user.common.core.vo.ResultVO;
import com.user.common.jwt.JwtUtil;
import com.user.propeties.WhiteListProperties;
import io.jsonwebtoken.ExpiredJwtException;
import org.apache.commons.lang3.StringUtils;
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.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
public class TokenFilter implements GlobalFilter, Ordered {

    @Autowired
    ImageProperties imageProperties;

    @Autowired
    WhiteListProperties whiteListProperties;
    
    @Override
    public int getOrder() {
        return -100;
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String uri = exchange.getRequest().getPath().value();

        if (whiteListProperties.getList().contains(uri) || uri.startsWith(imageProperties.getMapping())) {
            return chain.filter(exchange);
        }
        //HttpHeaders.AUTHORIZATION
        String token = exchange.getRequest().getHeaders().getFirst(HttpHeaders.AUTHORIZATION);
        if (StringUtils.isEmpty(token)) {
            return noAuth(exchange, "请传入令牌");
        }
        try {
            JwtUtil.parse(token);
        } catch (ExpiredJwtException e) {
            return noAuth(exchange, "令牌已过期");
        } catch (Exception e) {
            return noAuth(exchange, "令牌格式错误");
        }
        return chain.filter(exchange);
    }

    private Mono<Void> noAuth(ServerWebExchange exchange, String message) {
        ServerHttpResponse response = exchange.getResponse();
        response.getHeaders().set(HttpHeaders.CONTENT_TYPE, "application/json;charset=utf-8");

        String jsonStr = JSONUtil.toJsonStr(ResultVO.failed(403, message));
        DataBuffer dataBuffer = response.bufferFactory().wrap(jsonStr.getBytes());
        return response.writeWith(Mono.just(dataBuffer));
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值