spring-cloud 整合zuul 权限控制 token
作用是当所有的路由请求到后台时,过滤掉允许访问的路由后,需要一个token验证才可以访问到后台。
假设现在注册中心有两个服务service1 port 8001 、service2 port 8002
现在想要访问到这两个服务就需要token验证,新建一个zuul工程配置service1,service2的请求路由过滤。
第一步 项目中引入使用的jar包
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-zuul</artifactId> </dependency>
第二步 过滤器
import com.netflix.zuul.ZuulFilter; import com.netflix.zuul.context.RequestContext; import javax.servlet.http.HttpServletRequest; public class Filter extends ZuulFilter { /** * 返回一个字符串代表过滤器的类型 * pre表示被路由之前 */ @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(); String accessToken = String.valueOf(request.getParameter("Token")); if(!accessToken.equals("zz")) { ctx.setSendZuulResponse(false); ctx.setResponseStatusCode(401); return null; } return null; } }
第三步 写配置文件 将service1和service2配置路由
spring.application.name=Service-Gateway server.port=8003 # routes to service1 zuul.routes.service1.path=/service1/** zuul.routes.service1.serviceId=service1 # routes to service2 zuul.routes.service2.path=/service2/** zuul.routes.service2.serviceId=service2 eureka.client.serviceUrl.defaultZone=http://localhost:8761/eureka/spring.application.name=Service-Gateway server.port=8003 # routes to service1 zuul.routes.service1.path=/service1/** zuul.routes.service1.serviceId=service1 # routes to service2 zuul.routes.service2.path=/service2/** zuul.routes.service2.serviceId=service2 eureka.client.serviceUrl.defaultZone=http://localhost:8761/eureka/
第四步 过滤器书写之后就可以将这个bean引入主程序
1 import org.springframework.boot.builder.SpringApplicationBuilder; 2 import org.springframework.cloud.client.SpringCloudApplication; 3 import org.springframework.cloud.netflix.zuul.EnableZuulProxy; 4 import org.springframework.context.annotation.Bean; 5 6 import com.zz.springcloud.zuulfilter.Filter; 7 8 @EnableZuulProxy 9 @SpringCloudApplication 10 public class GateWayApplication { 11 12 public static void main(String[] args) { 13 new SpringApplicationBuilder(GateWayApplication.class).web(true).run(args); 14 } 15 16 @Bean 17 public Filter getFilter() { 18 return new Filter(); 19 } 20 21 }
嗯,这就配置好了,easy