spring cloud--Zuul实现登录拦截过滤

1.pom依赖

    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-zuul</artifactId>
    </dependency>

    <!-- 配置中心客户端 -->
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-config-client</artifactId>
    </dependency>

    <dependency>
        <groupId>io.jsonwebtoken</groupId>
        <artifactId>jjwt</artifactId>
    </dependency>

    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
    </dependency>

    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <scope>test</scope>
    </dependency>
    <!-- 热部署 -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-devtools</artifactId>
    </dependency>

    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
    </dependency>
    <!--暴露各种指标 -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-actuator</artifactId>
    </dependency>


    <!-- 配置文件自动映射 -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-configuration-processor</artifactId>
        <optional>true</optional>
    </dependency>
	<!--工具包 -->
    <dependency>
        <groupId>com.xu.common</groupId>
        <artifactId>com-xu-common</artifactId>
        <version>0.0.1</version>
    </dependency>
    

</dependencies>

2.application.yml配置

    spring:
        profiles:
            active: ${config_profile:dev}
        application:
            name: com-xu-gate
        http:
             multipart:
               maxFileSize: -1
               maxRequestSize: -1
    server:
      port: 6060 #启动端口
    //  undertow:
    //    worker-threads: 16 # 阻塞任务线程池, 当执行类似servlet请求阻塞操作, undertow会从这个线程池中取得线程,它的值设置取决于系统的负载
        
    #
    zuul:
      sensitiveHeaders:  
      add-host-header: true   #可以重定向
      host:
        socket-timeout-millis: 10000
        connect-timeout-millis: 5000
    //    max-per-route-connections: 100 #每个route可用的最大连接数,默认值是20
    //    max-total-connections: 1000 #每个服务的http客户端连接池最大连接,默认是200
    // semaphore:
    //   max-semaphores: 500 #The maximum number of total semaphores for Hystrix.默认100
    
    gate:
      ignore:
        startWith: /static
        contain: .
      oauth:
        prefix: /api
      login:
        control: off    #登录开关,on:表示需要登录才能下单。off:表示支持免登陆下单
    
      jwt:
        secret: Xe*g@1jda
        expiration: 7200
        header: access-token

zuul:
  routes:
    middle:
      path: /admin/**
      //serviceId: com-xu-admin
      url: http://127.0.0.1:6071/
product:
  path: /product/**
  //serviceId: com-cloud-product
  url: http://127.0.0.1:6073/

order:
  path: /order/**
  //serviceId: com-cloud-order
  url: http://127.0.0.1:6074/

satisitcs:
  path: /statistics/**
  #serviceId: com-cloud-satisitcs
  url: http://127.0.0.1:6075/

3.启动类配置
@SpringBootApplication
@EnableZuulProxy
@ComponentScan(basePackages = “com.xu”)
public class GateBootstrap {

public static void main(String[] args) {
    SpringApplication.run(GateBootstrap.class, args);
}

@Bean
public CorsFilter corsFilter() {
    final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    final CorsConfiguration config = new CorsConfiguration();
    config.setAllowCredentials(true); // 允许cookies跨域
    config.addAllowedOrigin("*");// 允许向该服务器提交请求的URI,*表示全部允许。。这里尽量限制来源域,比如http://xxxx:8080
    config.addAllowedHeader("*");// 允许访问的头信息,*表示全部
    config.setMaxAge(18000L);// 预检请求的缓存时间(秒),即在这个时间段里,对于相同的跨域请求不会再预检了
    config.addAllowedMethod("*");// 允许提交请求的方法,*表示全部允许,也可以单独设置GET、PUT等
    source.registerCorsConfiguration("/**", config);
    return new CorsFilter(source);
}

}
4.过滤器代码
@Slf4j
@Component
public class LoginFilter extends ZuulFilter {

@Autowired
private RedisHelper redisHelper;

//非拦截地址
private List<String> paths;
public LoginFilter() {
	super();
	paths = new ArrayList<>();
	paths.add("/login/logining");
	paths.add("/login/checkCode");
	paths.add("/ui/**");
	paths.add("/**/swagger**/**");
	paths.add("/**/v2/api-docs");
	paths.add("/**/*.css");
	paths.add("/**/*.jpg");
	paths.add("/**/*.png");
	paths.add("/**/*.gif");
	paths.add("/**/*.js");
	paths.add("/**/*.svg");
}


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

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

@Override
public boolean shouldFilter() {
	RequestContext requestContext = RequestContext.getCurrentContext();
	HttpServletRequest request = requestContext.getRequest();
	String uri=request.getRequestURI();
	log.info("uri:{}", uri);
	PathMatcher matcher = new AntPathMatcher();
	Optional<String> optional =paths.stream().filter(t->matcher.match(t,uri)).findFirst();
	return !optional.isPresent();
}

@Override
public Object run() {
	RequestContext ctx = RequestContext.getCurrentContext();
	HttpServletRequest request = ctx.getRequest();
	log.info("send  {} request to {} ",request.getMethod(),request.getRequestURL().toString());
	String accessToken=request.getHeader("access-token");
	if(StrUtil.isEmpty(accessToken)){
		accessToken = request.getParameter("token");
	}
	if(StringUtils.isEmpty(accessToken)) {
		log.warn("access token is empty");
		ctx.setSendZuulResponse(false);
		ctx.setResponseStatusCode(401);
		ctx.setResponseBody("access token is empty");
		return  null;
	}

	UserInfoDto userInfoDto = redisHelper.getCache(accessToken, UserInfoDto.class);
	//验证token正确性
	if(userInfoDto==null||!userInfoDto.getToken().equals(accessToken)) {
		log.warn("access token is invalid");
		ctx.setSendZuulResponse(false);
		ctx.setResponseStatusCode(401);
		ctx.setResponseBody("access token time out");
		return  null;
	}
	//放到request对象中,方便后续方法取值
	request.setAttribute(SysParamEnum.USERINFO.getKey(),userInfo);
	//刷新token
	redisHelper.putCacheWithExpireTime(accessToken,userInfo,3600);
	log.info("access token ok");
	return null;

}

}

欢迎评论点赞

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值