SpringCloud學習筆記(19)----Spring Cloud Netflix之服務網關Zuul自定義過濾器

  zuul不只只是路由,還能夠自定義過濾器來實現服務驗證。java

  實現案例:自定義過濾器,檢驗頭部是否帶有token,若是token=wangx,則經過校驗,若不存在或不爲wangx則返回提示token錯誤。spring

  擴展:通常狀況下,能夠採用JWT規範來作token的校驗。ide

  JWT:https://jwt.io/post

1. 自定義過濾器

package com.wangx.cloud.springcloud04zuul.filter;

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

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

public class MyFilter extends ZuulFilter {
    @Override
    public String filterType() {
        return "pre";
    }

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

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

    @Override
    public Object run() throws ZuulException {

        //獲取requestContext實例
        RequestContext requestContext = RequestContext.getCurrentContext();
        //獲取到request對象
        HttpServletRequest request = requestContext.getRequest();

        //獲取response對象

        HttpServletResponse response = requestContext.getResponse();
        // 判斷token是否爲wangx, 1 繼續往下執行,不然打印token error
        if (!"wangx".equals(request.getHeader("token"))) {
            try {
                //輸出流中寫入錯誤信息
                PrintWriter printWriter = response.getWriter();
                printWriter.write("token is error");
                printWriter.flush();
                printWriter.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        System.out.println("請求路徑爲:---" + request.getRequestURI());
        return null;
    }
}

2. 註冊自定義的過濾器

 @Bean
    public MyFilter myFilter() {
        return new MyFilter();
    }

3. 測試

  使用postman訪問:http://localhost:9876/spring-cloud-consumer/user/1測試

  

 

相關文章
相關標籤/搜索