第十七节 SpringBoot集成GateWay+JWT

亮子 2021-07-15 14:18:13 17177 0 0 0

1、添加依赖

        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-gateway</artifactId>
        </dependency>
        <dependency>
            <groupId>io.jsonwebtoken</groupId>
            <artifactId>jjwt</artifactId>
            <version>0.9.1</version>
        </dependency>

2、配置文件

1)、配置文件

#使用服务发现路由
spring.cloud.gateway.discovery.locator.enabled=true
#服务路由名小写
spring.cloud.gateway.discovery.locator.lower-case-service-id=true

#设置路由id
spring.cloud.gateway.routes[0].id=SERVER-SHOP-USER
spring.cloud.gateway.routes[0].uri=lb://SERVER-SHOP-USER
spring.cloud.gateway.routes[0].predicates[0]=Path=/user/**
spring.cloud.gateway.routes[0].filters=StripPrefix=1

# CORS
spring.cloud.gateway.globalcors.cors-configurations.[/**].allowed-origins=*
spring.cloud.gateway.globalcors.cors-configurations.[/**].allowedHeaders=*
spring.cloud.gateway.globalcors.cors-configurations.[/**].allowedMethods=*

2)、配置类

@Configuration
public class RoutesConfiguration {

    @Bean
    public RouteLocator customRouteLocator(RouteLocatorBuilder builder) {
        return builder.routes().route(predicateSpec ->
                predicateSpec.path("/auth/**").uri("lb://auth-service").id("auth-service")
        ).build();
    }

}

3、过滤器

package com.shenmazong.demoservergateway.filter;

import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;

@Configuration
public class GatewayFilter implements GlobalFilter, Ordered {

    /**
     * 全局过滤
     * @param exchange
     * @param chain
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 获取Request、Response对象
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        // 解决中文乱码问题
        HttpHeaders headers = response.getHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);

        // 打印输出URI
        String requestUrl = exchange.getRequest().getURI().getRawPath();
        System.out.println(requestUrl);
        System.out.println(request.getURI());

        // lanjie
        String token = request.getHeaders().getFirst("token");
        if(StringUtils.isEmpty(token)) {
            String msg = "{name:'david'}";
            DataBuffer dataBuffer = response.bufferFactory().wrap(msg.getBytes(StandardCharsets.UTF_8));
            return response.writeWith(Mono.just(dataBuffer));
        }

        // 放行
        return chain.filter(exchange);
    }

    /**
     * 排序,越小越先执行
     * @return
     */
    @Override
    public int getOrder() {
        return 0;
    }
}

参考文章