服务网关的安全性校验

通过【Java】Spring Cloud学习笔记02我们知道微服务的网关具有中转功能,服务网关还有个作用就是接口的安全性校验,这个时候就需要通过 gateway 进行统一拦截。
1、新建一个类 ApiGlobalFilter 并继承 GlobalFilter:

<span class='yzk_title_1492'>【Java】Spring Cloud学习笔记03</span>-Maxchen个人博客

import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
@Component
public class ApiGlobalFilter implements GlobalFilter {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String token = exchange.getRequest().getQueryParams().getFirst("token");
        if (StringUtils.isBlank(token)) {
            ServerHttpResponse response = exchange.getResponse();
            Map<String, Object> message = new HashMap<>();
            message.put("status", -1);
            message.put("data", "鉴权失败"); //如果token为空则鉴权失败
            byte[] bits = message.toString().getBytes(StandardCharsets.UTF_8);
            DataBuffer buffer = response.bufferFactory().wrap(bits);
            response.setStatusCode(HttpStatus.UNAUTHORIZED); //返回鉴权失败的信息
            response.getHeaders().add("Content-Type", "text/json;charset=UTF-8");
            return response.writeWith(Mono.just(buffer));
        }
        return chain.filter(exchange);
    }
}

2、接着浏览器输入地址http://localhost:8080/EUREKACLIENT/index则会因为token为空而返回鉴权失败的信息,在地址后面再添加token参数则会鉴权成功,带token的访问地址为:http://localhost:8080/EUREKACLIENT/index?token=1

<span class='yzk_title_1492'>【Java】Spring Cloud学习笔记03</span>-Maxchen个人博客<span class='yzk_title_1492'>【Java】Spring Cloud学习笔记03</span>-Maxchen个人博客

服务网关的错误拦截

1、Spring Cloud Gateway 为我们提供了一个名叫 DefaultErrorWebExceptionHandler 的类,通过继承它我们就可以对这些请求不到的服务进行错误处理。新建一个类 JsonExceptionHandler 并且继承 DefaultErrorWebExceptionHandler 类:

import org.springframework.boot.autoconfigure.web.ErrorProperties;
import org.springframework.boot.autoconfigure.web.ResourceProperties;
import org.springframework.boot.autoconfigure.web.reactive.error.DefaultErrorWebExceptionHandler;
import org.springframework.boot.web.reactive.error.ErrorAttributes;
import org.springframework.context.ApplicationContext;
import org.springframework.http.HttpStatus;
import org.springframework.web.reactive.function.server.*;

import java.util.HashMap;
import java.util.Map;

/**
 * 自定义异常处理
 * SpringBoot 提供了默认的异常处理类,这显然不符合我们的预期
 * 因此需要重写此类,返回统一的 JSON 格式
 */
public class JsonExceptionHandler extends DefaultErrorWebExceptionHandler {

    public JsonExceptionHandler(ErrorAttributes errorAttributes, ResourceProperties resourceProperties,
                                ErrorProperties errorProperties, ApplicationContext applicationContext) {
        super(errorAttributes, resourceProperties, errorProperties, applicationContext);
    }

    /**
     * 获取异常属性
     */
    @Override
    protected Map<String, Object> getErrorAttributes(ServerRequest request, boolean includeStackTrace) {
        int code = 500;
        Throwable error = super.getError(request);
        if (error instanceof org.springframework.cloud.gateway.support.NotFoundException) {
            code = 404;
        }
        return response(code, this.buildMessage(request, error));
    }

    /**
     * 指定响应处理方法为 JSON 处理的方法
     * @param errorAttributes
     */
    @Override
    protected RouterFunction<ServerResponse> getRoutingFunction(ErrorAttributes errorAttributes) {
        return RouterFunctions.route(RequestPredicates.all(), this::renderErrorResponse);
    }

    /**
     * 根据 code 获取对应的 HttpStatus
     * @param errorAttributes
     */
    @Override
    protected HttpStatus getHttpStatus(Map<String, Object> errorAttributes) {
        int statusCode = (int) errorAttributes.get("code");
        return HttpStatus.valueOf(statusCode);
    }

    /**
     * 构建异常信息
     * @param request
     * @param ex
     * @return
     */
    private String buildMessage(ServerRequest request, Throwable ex) {
        StringBuilder message = new StringBuilder("Failed to handle request [");
        message.append(request.methodName());
        message.append(" ");
        message.append(request.uri());
        message.append("]");
        if (ex != null) {
            message.append(": ");
            message.append(ex.getMessage());
        }
        return message.toString();
    }

    /**
     * 构建返回的 JSON 数据格式
     * @param status        状态码
     * @param errorMessage  异常信息
     * @return
     */
    public static Map<String, Object> response(int status, String errorMessage) {
        Map<String, Object> map = new HashMap<>();
        map.put("code", status);
        map.put("message", errorMessage);
        map.put("data", null);
        return map;
    }

}

2、将上述类加载到 Spring 容器中,因此还需要添加以下配置类:

<span class='yzk_title_1492'>【Java】Spring Cloud学习笔记03</span>-Maxchen个人博客

import org.springframework.beans.factory.ObjectProvider;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.boot.autoconfigure.web.ResourceProperties;
import org.springframework.boot.autoconfigure.web.ServerProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.web.reactive.error.ErrorAttributes;
import org.springframework.boot.web.reactive.error.ErrorWebExceptionHandler;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.codec.ServerCodecConfigurer;
import org.springframework.web.reactive.result.view.ViewResolver;

import java.util.Collections;
import java.util.List;

@SpringBootConfiguration
@EnableConfigurationProperties({ServerProperties.class, ResourceProperties.class})
public class ErrorHandlerConfiguration {

    private final ServerProperties serverProperties;

    private final ApplicationContext applicationContext;

    private final ResourceProperties resourceProperties;

    private final List<ViewResolver> viewResolvers;

    private final ServerCodecConfigurer serverCodecConfigurer;

    public ErrorHandlerConfiguration(ServerProperties serverProperties,
                                     ResourceProperties resourceProperties,
                                     ObjectProvider<List<ViewResolver>> viewResolversProvider,
                                     ServerCodecConfigurer serverCodecConfigurer,
                                     ApplicationContext applicationContext) {
        this.serverProperties = serverProperties;
        this.applicationContext = applicationContext;
        this.resourceProperties = resourceProperties;
        this.viewResolvers = viewResolversProvider.getIfAvailable(Collections::emptyList);
        this.serverCodecConfigurer = serverCodecConfigurer;
    }

    /**
     * gateway 启动时执行此方法,将 JsonExceptionHandler 注入到 Spring 容器中
     * 以便发生异常时执行自定义的 JsonExceptionHandler
     *
     * @param errorAttributes
     * @return
     */
    @Bean
    @Order(Ordered.HIGHEST_PRECEDENCE)
    public ErrorWebExceptionHandler errorWebExceptionHandler(ErrorAttributes errorAttributes) {
        JsonExceptionHandler exceptionHandler = new JsonExceptionHandler(
                errorAttributes,
                this.resourceProperties,
                this.serverProperties.getError(),
                this.applicationContext);
        exceptionHandler.setViewResolvers(this.viewResolvers);
        exceptionHandler.setMessageWriters(this.serverCodecConfigurer.getWriters());
        exceptionHandler.setMessageReaders(this.serverCodecConfigurer.getReaders());
        return exceptionHandler;
    }
}

3、最后重启整个工程分别输入http://localhost:8762/和http://localhost:8080/,发现使用错误拦截后的网页输出为JSON格式的形式:

<span class='yzk_title_1492'>【Java】Spring Cloud学习笔记03</span>-Maxchen个人博客
<span class='yzk_title_1492'>【Java】Spring Cloud学习笔记03</span>-Maxchen个人博客

记录你的想法-丰富你的知识
  • <span class='yzk_title_1668'>【Java】Spring Cloud学习笔记05</span>
    【Java】Spring Cloud学习笔记05
  • <span class='yzk_title_1601'>【Java】Spring Cloud学习笔记04</span>
    【Java】Spring Cloud学习笔记04
  • <span class='yzk_title_1425'>【Java】Spring Cloud学习笔记02</span>
    【Java】Spring Cloud学习笔记02
  • <span class='yzk_title_1416'>【Java】Spring Cloud学习笔记01</span>
    【Java】Spring Cloud学习笔记01
  • <span class='yzk_title_1402'>【Java】Spring boot学习笔记05</span>
    【Java】Spring boot学习笔记05
  • <span class='yzk_title_1394'>【Java】Spring boot学习笔记04</span>
    【Java】Spring boot学习笔记04
发表评论

坐等沙发