首页 > 编程语言 > 详细

Spring Cloud Zuul 添加 ZuulFilter

时间:2017-12-15 17:19:02      阅读:595      评论:0      收藏:0      [点我收藏+]

紧接着上篇随笔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

原文:http://www.cnblogs.com/dzpykj/p/8044001.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!