使用網關zuul過濾器登錄鑒權
1、新建一個filter包
filte有很多種 pre、post。
2、新建一個類LoginFilter,實現ZuulFilter,重寫里面的四個方法(可以根據業務建很多個過濾器filter)
filterType/filterOrder/shouldFilter/run
1)、filterType返回過濾器類型,前置類型為return PRE_TYPe,引入類FilterConstants,在類中可以看到各類filter定義
有以下幾種
public static final String ERROR_TYPE = "error";
public static final String POST_TYPE = "post";
public static final String PRE_TYPE = "pre";
public static final String ROUTE_TYPE = "route";
public static final String FORWARD_LOCATION_PREFIX = "forward:";
2)、在filterOrder中return 4,要解碼后,PRE_DECORATION_FILTER_ORDER之前。order越小越優先執行
3)、shouldFilter為過濾器是否生效,確認URI為save方法則需要運行攔截(登錄鑒權),如果不是則不攔截
RequestContext requestContext= RequestContext.getCurrentContext();
HttpServletRequest httpServletRequest=requestContext.getRequest();
System.out.println(httpServletRequest.getRequestURI());///apigateway/order/api/v1/orderfeignhystrix/save
System.out.println(httpServletRequest.getRequestURL());//http://192.168.136.128:9000/apigateway/order/api/v1/orderfeignhystrix/save
if ("/apigateway/order/api/v1/orderfeignhystrix/save".equalsIgnoreCase(httpServletRequest.getRequestURI())) //小的項目可以按照一個一個編寫,如果大的項目會使用ACL控制
{
return true;
}
return false;
4)、run為過濾的方法,通過token來確認是否登錄,如果沒有token則提示攔截了,並反饋未認證401
System.out.println("l攔截了!");
//JWT
RequestContext requestContext=RequestContext.getCurrentContext();
HttpServletRequest request=requestContext.getRequest();
//token對象
String token=request.getHeader("token");
if (StringUtils.isBlank(token))
{
token=request.getParameter("token");
}
if (StringUtils.isBlank(token))
{
requestContext.setSendZuulResponse(false);
requestContext.setResponseStatusCode(HttpStatus.SC_UNAUTHORIZED);
}
return null;
看下JWT和token技術
3、在類頂部加注解,@Component,讓Spring掃描
4、測試
http://192.168.136.128:9000/apigateway/order/api/v1/orderfeignhystrix/save?userId=2&productId=2&token=333,可以訪問
http://192.168.136.128:9000/apigateway/order/api/v1/orderfeignhystrix/save?userId=2&productId=2訪問不了
