SpringCloud Gateway鑒權和跨域解決方案
一、Gateway鑒權實現(xiàn)方案
網(wǎng)關是介于客戶端和服務器端之間的中間層,所有的外部請求都會先經(jīng)過 網(wǎng)關這一層。也就是說,API 的實現(xiàn)方面更多的考慮業(yè)務邏輯,而安全、性能、監(jiān)控可以交由 網(wǎng)關來做,這樣既提高業(yè)務靈活性又不缺安全性。
RBAC(Role-Based Access Control)基于角色訪問控制,目前使用最為廣泛的權限模型。相信大家對這種權限模型已經(jīng)比較了解了。此模型有三個用戶、角色和權限,在傳統(tǒng)的權限模型用戶直接關聯(lián)加了角色,解耦了用戶和權限,使得權限系統(tǒng)有了更清晰的職責劃分和更高的靈活度
1、添加依賴
<dependency> <groupId>io.jsonwebtoken</groupId> <artifactId>jjwt</artifactId> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>RELEASE</version> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-gateway</artifactId> </dependency>
2、實現(xiàn)代碼
@Configuration @Component public class AuthGlobalFilter implements GlobalFilter, Ordered { @Autowired JwtTokenUtil jwtTokenUtil; @Autowired(required = false) JedisUtil jedisUtil; private String cachePrefix = "km-gateway-"; @Value("${spring.redis.expired}") private Integer expiredSecond;//600000,10m @Override public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) { ServerHttpRequest request = exchange.getRequest(); HttpHeaders httpHeaders = request.getHeaders(); exchange.getRequest().getURI(); String requestUri = request.getPath().pathWithinApplication().value(); String token = null; if (httpHeaders != null && httpHeaders.containsKey("token") && !httpHeaders.get("token").isEmpty()) { token = httpHeaders.get("token").get(0); } // AuthenticateRequest if (StringUtil.isBlank(token)) { // String message = "You current request uri do not have permission or auth."; // return getVoidMono(exchange, message); return chain.filter(exchange); } String userAccountId = jwtTokenUtil.getUserAccountIdFromToken(token); boolean hasPermission = checkPermission(userAccountId, requestUri); String username = jwtTokenUtil.getUsernameFromToken(token); String redisSetUrlKey = cachePrefix.concat("url-").concat(username); // log.info("###### hasPermission.2=" + hasPermission); if (hasPermission) { jedisUtil.SetAndTime(redisSetUrlKey, expiredSecond, requestUri); } else { String message = "You current request uri do not have permission or auth."; // log.warn(message); return getVoidMono(exchange, message); } jwtTokenUtil.isValid(token); return chain.filter(exchange); } @Override public int getOrder() { return 0; } //根據(jù)角色權限進行權限控制 private boolean checkPermission(String userId, String requestUrl) { return false; } private Mono<Void> getVoidMono(ServerWebExchange exchange, String body) { exchange.getResponse().setStatusCode(HttpStatus.OK); byte[] bytes = body.getBytes(StandardCharsets.UTF_8); DataBuffer buffer = exchange.getResponse().bufferFactory().wrap(bytes); return exchange.getResponse().writeWith(Flux.just(buffer)); } }
二、Gateway跨域解決方案
在SpringCloud項目中,前后端分離目前很常見,在調(diào)試時會遇到前端頁面通過不同域名或IP訪問微服務的后臺,此時,如果不加任何配置,前端頁面的請求會被瀏覽器跨域限制攔截,所以,業(yè)務服務常常會添加跨域配置
1、配置類實現(xiàn)
@Configuration public class GulimallCorsConfiguration { /** * 添加跨域過濾器 * @return */ @Bean public CorsWebFilter corsWebFilter(){ //基于url跨域,選擇reactive包下的 UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); // 跨域配置信息 CorsConfiguration configuration = new CorsConfiguration(); // 允許跨域的頭 configuration.addAllowedHeader("*"); // 允許跨域的請求方式 configuration.addAllowedMethod("*"); // 允許跨域的請求來源 configuration.addAllowedOrigin("*"); // 是否允許攜帶cookie跨域 configuration.setAllowCredentials(true); // 任意url都要進行跨域配置 source.registerCorsConfiguration("/**", configuration); return new CorsWebFilter(source); } }
注: SpringCloudGateWay中跨域配置不起作用,原因是SpringCloudGetway是 Springwebflux的而不是SpringWebMvc的,所以我們需要導入的包導入錯了
2、配置文件配置
server: port: 10010 spring: application: name: gatewayservice cloud: gateway: globalcors: cors-configurations: '[/**]': allowedOrigins: "https://www.xx.com" # 允許那些網(wǎng)站跨域訪問 allowedMethods: "GET" # 允許那些Ajax方式的跨域請求 allowedHeaders: "*" # 允許請求頭攜帶信息 allowCredentials: "*" # 允許攜帶cookie maxAge: 360000 # 這次跨域有效期于相同的跨域請求不會再預檢
到此這篇關于SpringCloud Gateway鑒權和跨域解決方案的文章就介紹到這了,更多相關SpringCloud Gateway鑒權和跨域內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
javax.persistence中@Column定義字段類型方式
這篇文章主要介紹了javax.persistence中@Column定義字段類型方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-11-11IntelliJ IDEA打開多個Maven的module且相互調(diào)用代碼的方法
這篇文章主要介紹了IntelliJ IDEA打開多個Maven的module且相互調(diào)用代碼的方法,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2019-02-02Spring Boot 整合 Shiro+Thymeleaf過程解析
這篇文章主要介紹了Spring Boot 整合 Shiro+Thymeleaf過程解析,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2019-10-10關于log4j日志擴展---自定義PatternLayout
這篇文章主要介紹了關于log4j日志擴展---自定義PatternLayout,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-12-12Spring中AOP概念與兩種動態(tài)代理模式原理詳解
AOP是面向切面編程的技術,AOP基于IoC基礎,是對OOP的有益補充,流行的AOP框架有Sping AOP、AspectJ,這篇文章主要給大家介紹了關于Spring中AOP概念與兩種動態(tài)代理模式原理的相關資料,需要的朋友可以參考下2021-10-10SpringBoot日志進階實戰(zhàn)之Logback配置經(jīng)驗和方法
本文給大家介紹在SpringBoot中使用Logback配置日志的經(jīng)驗和方法,并提供了詳細的代碼示例和解釋,包括:滾動文件、異步日志記錄、動態(tài)指定屬性、日志級別、配置文件等常用功能,覆蓋日常Logback配置開發(fā)90%的知識點,感興趣的朋友跟隨小編一起看看吧2023-06-06