Spring Cloud Zuul 添加 ZuulFilter

Posted PinBo

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Spring Cloud Zuul 添加 ZuulFilter相关的知识,希望对你有一定的参考价值。

紧接着上篇随笔Spring Cloud Zuul写,添加过滤器,进行权限验证

1.添加过滤器

package com.dzpykj.filter;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Component;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;

@Component
public class AccessFilter extends ZuulFilter {

    @Override
    public String filterType() {
        return "pre";
    }

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

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() {
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();
        Object accessToken = request.getParameter("accessToken");
        if (request.getRequestURI().contains("myOrder")) {
            if (accessToken == null) {
                ctx.setSendZuulResponse(false);
                ctx.setResponseStatusCode(401);
                try {
                    ctx.getResponse().getWriter().write("You are unauthorized");
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return null;
            }
        }
        return null;
    }

}

 

2.访问http://127.0.0.1:8767/service1/myOrder;http://127.0.0.1:8767/service2/myOrder

3.源码:https://github.com/PinBo1991/springcloud

以上是关于Spring Cloud Zuul 添加 ZuulFilter的主要内容,如果未能解决你的问题,请参考以下文章

spring-cloud-zuul-ratelimit 配置

spring cloud 学习笔记--网关zuul学习

Spring Cloud Zuul - 自定义错误过滤器

7Spring -Cloud-路由网管Spring Cloud Zuul

Zuul上实现限流(spring-cloud-zuul-ratelimit)

最全面的改造Zuul网关为Spring Cloud Gateway(包含Zuul核心实现和Spring Cloud Gateway核心实现)