当前位置:网站首页>Gateway uses global filter for token verification

Gateway uses global filter for token verification

2022-06-22 05:03:00 guomz

Introduce dependencies

<dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>

Why not use interceptors interceptor

Use interceptor Need to introduce spring-boot-starter-web This dependence , But this dependency can lead to gateway Service failed to start , Report No qualifying bean of type 'org.springframework.core.convert.ConversionService' available It's abnormal , as a result of gateway Can't be in tomcat Etc servlet Running in the container , But needs netty, If this error is reported, the spring-boot-starter-web Remove the dependency .

Write filters

@Component
@Slf4j
public class AuthFilter implements GlobalFilter, Ordered {

    private AntPathMatcher matcher = new AntPathMatcher();

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        String path = request.getURI().getPath();
        log.info(" Request path : {}", path);
        if (matcher.match("/api/**/auth/**", path)){
            if (getUserId(request) == null){
                log.error("token Incorrect ");
                out(exchange.getResponse(), ResultCodeEnum.LOGIN_AUTH);
            }
        }
        return chain.filter(exchange);
    }

    private Long getUserId(ServerHttpRequest request){
        List<String> tokens = request.getHeaders().get("token");
        if (tokens == null || StringUtils.isEmpty(tokens)){
            log.error(" Request not carried token");
            return null;
        }
        return JwtUtil.getUserId(tokens.get(0));
    }

    /**
     * api Interface authentication failed and returned data 
     * @param response
     * @return
     */
    private Mono<Void> out(ServerHttpResponse response, ResultCodeEnum resultCodeEnum) {
        Result result = Result.build(null, resultCodeEnum);
        byte[] bits = JSONObject.toJSONString(result).getBytes(StandardCharsets.UTF_8);
        DataBuffer buffer = response.bufferFactory().wrap(bits);
        // Specified encoding , Otherwise, there will be garbled Chinese in the browser 
        response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
        return response.writeWith(Mono.just(buffer));
    }

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

The filter class needs to implement GlobalFilter Interface implementation filter Method , Current http Request object request adopt ServerWebExchange Of getRequest() Method to get ,request Object's getURI().getPath() Method to get the requested address ( For example, request access localhost:8080/test/name The address is /test/name).
Use AntPathMatcher You can use a matching string to match the request address , Tape in the example auth That is, the access that needs to be logged in has been matched and intercepted , After through request obtain header Medium token Conduct token Validation of the . If token Validation failed , Use out Method to output an error message , Here, the output object is processed json After serialization, it is converted to bit Stream output .
Realization Order Interface is used to define filter priority , I.e. implementation getOrder() Method , When there are multiple filters , The smaller the value returned by this method, the higher the priority .

原网站

版权声明
本文为[guomz]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202221000456330.html