SpringCloud Gateway鑒權(quán)和跨域解決方案
一、Gateway鑒權(quán)實現(xiàn)方案
網(wǎng)關(guān)是介于客戶端和服務(wù)器端之間的中間層,所有的外部請求都會先經(jīng)過 網(wǎng)關(guān)這一層。也就是說,API 的實現(xiàn)方面更多的考慮業(yè)務(wù)邏輯,而安全、性能、監(jiān)控可以交由 網(wǎng)關(guān)來做,這樣既提高業(yè)務(wù)靈活性又不缺安全性。
RBAC(Role-Based Access Control)基于角色訪問控制,目前使用最為廣泛的權(quán)限模型。相信大家對這種權(quán)限模型已經(jīng)比較了解了。此模型有三個用戶、角色和權(quán)限,在傳統(tǒng)的權(quán)限模型用戶直接關(guān)聯(lián)加了角色,解耦了用戶和權(quán)限,使得權(quá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ù)角色權(quá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項目中,前后端分離目前很常見,在調(diào)試時會遇到前端頁面通過不同域名或IP訪問微服務(wù)的后臺,此時,如果不加任何配置,前端頁面的請求會被瀏覽器跨域限制攔截,所以,業(yè)務(wù)服務(wù)常常會添加跨域配置
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的,所以我們需要導(dǎo)入的包導(dǎo)入錯了
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 # 這次跨域有效期于相同的跨域請求不會再預(yù)檢到此這篇關(guān)于SpringCloud Gateway鑒權(quán)和跨域解決方案的文章就介紹到這了,更多相關(guān)SpringCloud Gateway鑒權(quán)和跨域內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
javax.persistence中@Column定義字段類型方式
這篇文章主要介紹了javax.persistence中@Column定義字段類型方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-11-11
IntelliJ IDEA打開多個Maven的module且相互調(diào)用代碼的方法
這篇文章主要介紹了IntelliJ IDEA打開多個Maven的module且相互調(diào)用代碼的方法,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2019-02-02
Spring Boot 整合 Shiro+Thymeleaf過程解析
這篇文章主要介紹了Spring Boot 整合 Shiro+Thymeleaf過程解析,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習或者工作具有一定的參考學(xué)習價值,需要的朋友可以參考下2019-10-10
關(guān)于log4j日志擴展---自定義PatternLayout
這篇文章主要介紹了關(guān)于log4j日志擴展---自定義PatternLayout,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-12-12
Spring中AOP概念與兩種動態(tài)代理模式原理詳解
AOP是面向切面編程的技術(shù),AOP基于IoC基礎(chǔ),是對OOP的有益補充,流行的AOP框架有Sping AOP、AspectJ,這篇文章主要給大家介紹了關(guān)于Spring中AOP概念與兩種動態(tài)代理模式原理的相關(guān)資料,需要的朋友可以參考下2021-10-10
SpringBoot日志進階實戰(zhàn)之Logback配置經(jīng)驗和方法
本文給大家介紹在SpringBoot中使用Logback配置日志的經(jīng)驗和方法,并提供了詳細的代碼示例和解釋,包括:滾動文件、異步日志記錄、動態(tài)指定屬性、日志級別、配置文件等常用功能,覆蓋日常Logback配置開發(fā)90%的知識點,感興趣的朋友跟隨小編一起看看吧2023-06-06

