SpringCloud Gateway鑒權(quán)和跨域解決方案
一、Gateway鑒權(quán)實(shí)現(xiàn)方案
網(wǎng)關(guān)是介于客戶端和服務(wù)器端之間的中間層,所有的外部請(qǐng)求都會(huì)先經(jīng)過(guò) 網(wǎng)關(guān)這一層。也就是說(shuō),API 的實(shí)現(xiàn)方面更多的考慮業(yè)務(wù)邏輯,而安全、性能、監(jiān)控可以交由 網(wǎng)關(guān)來(lái)做,這樣既提高業(yè)務(wù)靈活性又不缺安全性。
RBAC(Role-Based Access Control)基于角色訪問(wèn)控制,目前使用最為廣泛的權(quán)限模型。相信大家對(duì)這種權(quán)限模型已經(jīng)比較了解了。此模型有三個(gè)用戶、角色和權(quán)限,在傳統(tǒng)的權(quán)限模型用戶直接關(guān)聯(lián)加了角色,解耦了用戶和權(quán)限,使得權(quán)限系統(tǒng)有了更清晰的職責(zé)劃分和更高的靈活度
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、實(shí)現(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ù)角色權(quán)限進(jìn)行權(quán)限控制 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項(xiàng)目中,前后端分離目前很常見,在調(diào)試時(shí)會(huì)遇到前端頁(yè)面通過(guò)不同域名或IP訪問(wèn)微服務(wù)的后臺(tái),此時(shí),如果不加任何配置,前端頁(yè)面的請(qǐng)求會(huì)被瀏覽器跨域限制攔截,所以,業(yè)務(wù)服務(wù)常常會(huì)添加跨域配置
1、配置類實(shí)現(xiàn)
@Configuration public class GulimallCorsConfiguration { /** * 添加跨域過(guò)濾器 * @return */ @Bean public CorsWebFilter corsWebFilter(){ //基于url跨域,選擇reactive包下的 UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); // 跨域配置信息 CorsConfiguration configuration = new CorsConfiguration(); // 允許跨域的頭 configuration.addAllowedHeader("*"); // 允許跨域的請(qǐng)求方式 configuration.addAllowedMethod("*"); // 允許跨域的請(qǐng)求來(lái)源 configuration.addAllowedOrigin("*"); // 是否允許攜帶cookie跨域 configuration.setAllowCredentials(true); // 任意url都要進(jìn)行跨域配置 source.registerCorsConfiguration("/**", configuration); return new CorsWebFilter(source); } }
注: SpringCloudGateWay中跨域配置不起作用,原因是SpringCloudGetway是 Springwebflux的而不是SpringWebMvc的,所以我們需要導(dǎo)入的包導(dǎo)入錯(cuò)了
2、配置文件配置
server: port: 10010 spring: application: name: gatewayservice cloud: gateway: globalcors: cors-configurations: '[/**]': allowedOrigins: "https://www.xx.com" # 允許那些網(wǎng)站跨域訪問(wèn) allowedMethods: "GET" # 允許那些Ajax方式的跨域請(qǐng)求 allowedHeaders: "*" # 允許請(qǐng)求頭攜帶信息 allowCredentials: "*" # 允許攜帶cookie maxAge: 360000 # 這次跨域有效期于相同的跨域請(qǐng)求不會(huì)再預(yù)檢
到此這篇關(guān)于SpringCloud Gateway鑒權(quán)和跨域解決方案的文章就介紹到這了,更多相關(guān)SpringCloud Gateway鑒權(quán)和跨域內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
javax.persistence中@Column定義字段類型方式
這篇文章主要介紹了javax.persistence中@Column定義字段類型方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-11-11IntelliJ IDEA打開多個(gè)Maven的module且相互調(diào)用代碼的方法
這篇文章主要介紹了IntelliJ IDEA打開多個(gè)Maven的module且相互調(diào)用代碼的方法,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2019-02-02Java實(shí)現(xiàn)的JSONUtil工具類與用法示例
這篇文章主要介紹了Java實(shí)現(xiàn)的JSONUtil工具類與用法,結(jié)合實(shí)例形式分析了Java操作json格式數(shù)據(jù)工具類JSONUtil的定義與簡(jiǎn)單使用技巧,需要的朋友可以參考下2018-07-07Spring Boot 整合 Shiro+Thymeleaf過(guò)程解析
這篇文章主要介紹了Spring Boot 整合 Shiro+Thymeleaf過(guò)程解析,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2019-10-10關(guān)于log4j日志擴(kuò)展---自定義PatternLayout
這篇文章主要介紹了關(guān)于log4j日志擴(kuò)展---自定義PatternLayout,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-12-12Spring中AOP概念與兩種動(dòng)態(tài)代理模式原理詳解
AOP是面向切面編程的技術(shù),AOP基于IoC基礎(chǔ),是對(duì)OOP的有益補(bǔ)充,流行的AOP框架有Sping AOP、AspectJ,這篇文章主要給大家介紹了關(guān)于Spring中AOP概念與兩種動(dòng)態(tài)代理模式原理的相關(guān)資料,需要的朋友可以參考下2021-10-10mybatis 忽略實(shí)體對(duì)象的某個(gè)屬性(2種方式)
這篇文章主要介紹了mybatis 忽略實(shí)體對(duì)象的某個(gè)屬性方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-06-06SpringBoot日志進(jìn)階實(shí)戰(zhàn)之Logback配置經(jīng)驗(yàn)和方法
本文給大家介紹在SpringBoot中使用Logback配置日志的經(jīng)驗(yàn)和方法,并提供了詳細(xì)的代碼示例和解釋,包括:滾動(dòng)文件、異步日志記錄、動(dòng)態(tài)指定屬性、日志級(jí)別、配置文件等常用功能,覆蓋日常Logback配置開發(fā)90%的知識(shí)點(diǎn),感興趣的朋友跟隨小編一起看看吧2023-06-06