gateway结合jwt的token校验,网关跨域处理

网关过滤

@Component
@Slf4j
public class JwtWebFilter implements GlobalFilter, Ordered {
    @Value("${jwt.secret_key}")
    private String secretKey;
    @Value("${jwt.excluded_auth_url}")
    private String excludedAuthUrl;
    @Override
    public int getOrder() {
        return -100;
    }
    /**
     * 过滤器
     *
     * @param exchange  链路处理
     * @param chain 拦截或放行
     * @return 鉴权结果
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        ServerHttpResponse resp = exchange.getResponse();
        ServerHttpRequest request = exchange.getRequest();
        String[] excludedAuthUrlArr = excludedAuthUrl.split(",");
        String path = request.getPath().value();
        List<String> tokenList = request.getHeaders().get("auth-token");
        //排除url直接放行
        if(!path.contains("/sastWeb/")){
            return chain.filter(exchange);
        }
        if (CollectionUtils.isEmpty(tokenList)) {
            log.info("JwtWebFilter.filter->请求未携带token");
            return authErro(resp,"登录过期,请重新登录");
        }
        String token = tokenList.get(0);
        //排除小程序端的的url直接放行
        if(Arrays.asList(excludedAuthUrlArr).contains(path)){
            return chain.filter(exchange);
        }
        //判断token是否过期
        if (JwtTokenUtils.isExpiration(token, secretKey)) {
            log.info("JwtWebFilter.filter->token时间过期");
            return authErro(resp,"登录过期,请重新登录");
        }
        return chain.filter(exchange);

    }

    /**
     * 认证错误输出
     *
     * @param resp 响应对象
     * @param mess 错误信息
     * @return 错误结果
     */
    private Mono<Void> authErro(ServerHttpResponse resp, String mess) {
        Gson gson=new Gson();
        resp.setStatusCode(HttpStatus.FORBIDDEN);
        resp.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
        ResponseVO<Object> resultData = ResponseVO.newInstance(ErrorCodeEnum.ErrorCode.NOT_ACCEPTABLE);
        String returnStr = "";
        try {
            returnStr = gson.toJson(resultData);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        DataBuffer buffer = resp.bufferFactory().wrap(returnStr.getBytes(StandardCharsets.UTF_8));
        return resp.writeWith(Flux.just(buffer));
    }

}

GlobalFilter是gateway里面的过滤器

网关添加跨域
jar依赖

<dependency>
			<groupId>io.jsonwebtoken</groupId>
			<artifactId>jjwt</artifactId>
			<version>0.9.1</version>
		</dependency>
@Configuration
public class GwCorsFilter {


    @Bean
    public CorsWebFilter corsFilter() {
        CorsConfiguration config = new CorsConfiguration();

        config.setAllowCredentials(true); // 允许cookies跨域
        config.addAllowedOriginPattern("*");// #允许向该服务器提交请求的URI,*表示全部允许,在SpringMVC中,如果设成*,会自动转成当前请求头中的Origin
        config.addAllowedHeader("*");// #允许访问的头信息,*表示全部
        config.setMaxAge(18000L);// 预检请求的缓存时间(秒),即在这个时间段里,对于相同的跨域请求不会再预检了
        config.addAllowedMethod("OPTIONS");// 允许提交请求的方法类型,*表示全部允许
        config.addAllowedMethod("HEAD");
        config.addAllowedMethod("GET");
        config.addAllowedMethod("PUT");
        config.addAllowedMethod("POST");
        config.addAllowedMethod("DELETE");
        config.addAllowedMethod("PATCH");
        config.addExposedHeader("auth-token");


        org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource source =
                new org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource(new PathPatternParser());
        source.registerCorsConfiguration("/**", config);

        return new CorsWebFilter(source);
    }
}

你可能感兴趣的:(技术积累,java,mybatis,gateway)