日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 前端技术 > javascript >内容正文

javascript

SpringCloud Gateway 集成 oauth2 实现统一认证授权_03

發布時間:2024/9/27 javascript 28 豆豆
生活随笔 收集整理的這篇文章主要介紹了 SpringCloud Gateway 集成 oauth2 实现统一认证授权_03 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

文章目錄

          • 一、網關搭建
            • 1. 引入依賴
            • 2. 配置文件
            • 3. 增加權限管理器
            • 4. 自定義認證接口管理類
            • 5. 增加網關層的安全配置
            • 6. 搭建授權認證中心
          • 二、搭建產品服務
            • 2.1. 創建boot項目
            • 2.2. 引入依賴
            • 2.3. controller
            • 2.4. 啟動類
            • 2.5. 配置
          • 四、測試驗證
            • 4.1. 啟動nacos
            • 4.2. 啟動認證中心
            • 4.3. 啟動產品服務
            • 4.3. 請求認證授權中心
            • 4.4. 網關請求產品模塊
            • 4.5. 獲取token
            • 4.6. 攜帶token請求產品服務
            • 4.7. 直接請求產品服務
            • 4.8. 請求結果比對
          • 五、總結

一、網關搭建
1. 引入依賴
<parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.3.2.RELEASE</version><relativePath/> <!-- lookup parent from repository --></parent><properties><spring.cloud-version>Hoxton.SR9</spring.cloud-version></properties><dependencies><!--安全認證框架--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-security</artifactId></dependency><!--security-oauth2整合--><dependency><groupId>org.springframework.security</groupId><artifactId>spring-security-oauth2-resource-server</artifactId></dependency><!--oauth2--><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-oauth2</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-jdbc</artifactId></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId></dependency><!--網關--><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-gateway</artifactId></dependency></dependencies><dependencyManagement><!--https://github.com/alibaba/spring-cloud-alibaba/wiki/%E7%89%88%E6%9C%AC%E8%AF%B4%E6%98%8E--><dependencies><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-dependencies</artifactId><version>${spring.cloud-version}</version><type>pom</type><scope>import</scope></dependency></dependencies></dependencyManagement>
2. 配置文件
server:port: 8081 spring:cloud:gateway:routes:- id: producturi: http://localhost:9000predicates:- Host=product.gblfy.com**- id: authuri: http://localhost:5000predicates:- Path=/oauth/token- id: skilluri: http://localhost:13000predicates:- Path=/skilldatasource:driver-class-name: com.mysql.cj.jdbc.Driverurl: jdbc:mysql://localhost:3306/auth-serv?characterEncoding=UTF-8&serverTimezone=GMT%2B8username: rootpassword: 123456
3. 增加權限管理器
package com.gblfy.gatewayserv.config;import lombok.extern.slf4j.Slf4j; import org.springframework.security.authorization.AuthorizationDecision; import org.springframework.security.authorization.ReactiveAuthorizationManager; import org.springframework.security.core.Authentication; import org.springframework.security.oauth2.provider.OAuth2Authentication; import org.springframework.security.web.server.authorization.AuthorizationContext; import org.springframework.stereotype.Component; import org.springframework.util.AntPathMatcher; import org.springframework.web.server.ServerWebExchange; import reactor.core.publisher.Mono;import java.util.Set; import java.util.concurrent.ConcurrentSkipListSet;@Slf4j @Component public class AccessManager implements ReactiveAuthorizationManager<AuthorizationContext> {private Set<String> permitAll = new ConcurrentSkipListSet<>();private static final AntPathMatcher antPathMatcher = new AntPathMatcher();public AccessManager() {permitAll.add("/");permitAll.add("/error");permitAll.add("/favicon.ico");permitAll.add("/**/v2/api-docs/**");permitAll.add("/**/swagger-resources/**");permitAll.add("/webjars/**");permitAll.add("/doc.html");permitAll.add("/swagger-ui.html");permitAll.add("/**/oauth/**");permitAll.add("/**/current/get");}/*** 實現權限驗證判斷*/@Overridepublic Mono<AuthorizationDecision> check(Mono<Authentication> authenticationMono, AuthorizationContext authorizationContext) {ServerWebExchange exchange = authorizationContext.getExchange();//請求資源String requestPath = exchange.getRequest().getURI().getPath();// 是否直接放行if (permitAll(requestPath)) {return Mono.just(new AuthorizationDecision(true));}return authenticationMono.map(auth -> {return new AuthorizationDecision(checkAuthorities(exchange, auth, requestPath));}).defaultIfEmpty(new AuthorizationDecision(false));}/*** 校驗是否屬于靜態資源** @param requestPath 請求路徑* @return*/private boolean permitAll(String requestPath) {return permitAll.stream().filter(r -> antPathMatcher.match(r, requestPath)).findFirst().isPresent();}//權限校驗private boolean checkAuthorities(ServerWebExchange exchange, Authentication auth, String requestPath) {if (auth instanceof OAuth2Authentication) {OAuth2Authentication athentication = (OAuth2Authentication) auth;String clientId = athentication.getOAuth2Request().getClientId();log.info("clientId is {}", clientId);}Object principal = auth.getPrincipal();log.info("用戶信息:{}", principal.toString());return true;} }
4. 自定義認證接口管理類
package com.gblfy.gatewayserv.config;import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.security.authentication.ReactiveAuthenticationManager; import org.springframework.security.core.Authentication; import org.springframework.security.oauth2.common.OAuth2AccessToken; import org.springframework.security.oauth2.common.exceptions.InvalidTokenException; import org.springframework.security.oauth2.provider.OAuth2Authentication; import org.springframework.security.oauth2.provider.token.TokenStore; import org.springframework.security.oauth2.server.resource.BearerTokenAuthenticationToken; import reactor.core.publisher.Mono;public class ReactiveJdbcAuthenticationManager implements ReactiveAuthenticationManager {Logger logger= LoggerFactory.getLogger(ReactiveJdbcAuthenticationManager.class);private TokenStore tokenStore;public ReactiveJdbcAuthenticationManager(TokenStore tokenStore){this.tokenStore = tokenStore;}@Overridepublic Mono<Authentication> authenticate(Authentication authentication) {return Mono.justOrEmpty(authentication).filter(a -> a instanceof BearerTokenAuthenticationToken).cast(BearerTokenAuthenticationToken.class).map(BearerTokenAuthenticationToken::getToken).flatMap((accessToken ->{logger.info("accessToken is :{}",accessToken);OAuth2AccessToken oAuth2AccessToken = this.tokenStore.readAccessToken(accessToken);//根據access_token從數據庫獲取不到OAuth2AccessTokenif(oAuth2AccessToken == null){return Mono.error(new InvalidTokenException("invalid access token,please check"));}else if(oAuth2AccessToken.isExpired()){return Mono.error(new InvalidTokenException("access token has expired,please reacquire token"));}OAuth2Authentication oAuth2Authentication =this.tokenStore.readAuthentication(accessToken);if(oAuth2Authentication == null){return Mono.error(new InvalidTokenException("Access Token 無效!"));}else {return Mono.just(oAuth2Authentication);}})).cast(Authentication.class);} }
5. 增加網關層的安全配置
package com.gblfy.gatewayserv.config;import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.HttpMethod; import org.springframework.security.authentication.ReactiveAuthenticationManager; import org.springframework.security.config.web.server.SecurityWebFiltersOrder; import org.springframework.security.config.web.server.ServerHttpSecurity; import org.springframework.security.oauth2.provider.token.store.JdbcTokenStore; import org.springframework.security.oauth2.server.resource.web.server.ServerBearerTokenAuthenticationConverter; import org.springframework.security.web.server.SecurityWebFilterChain; import org.springframework.security.web.server.authentication.AuthenticationWebFilter;import javax.sql.DataSource;@Configuration public class SecurityConfig {private static final String MAX_AGE = "18000L";@Autowiredprivate DataSource dataSource;@Autowiredprivate AccessManager accessManager;@BeanSecurityWebFilterChain webFluxSecurityFilterChain(ServerHttpSecurity http) throws Exception{//token管理器ReactiveAuthenticationManager tokenAuthenticationManager = new ReactiveJdbcAuthenticationManager(new JdbcTokenStore(dataSource));//認證過濾器AuthenticationWebFilter authenticationWebFilter = new AuthenticationWebFilter(tokenAuthenticationManager);authenticationWebFilter.setServerAuthenticationConverter(new ServerBearerTokenAuthenticationConverter());http.httpBasic().disable().csrf().disable().authorizeExchange().pathMatchers(HttpMethod.OPTIONS).permitAll().anyExchange().access(accessManager).and()//oauth2認證過濾器.addFilterAt(authenticationWebFilter, SecurityWebFiltersOrder.AUTHENTICATION);return http.build();} }

這個類是SpringCloug Gateway 與 Oauth2整合的關鍵,通過構建認證過濾器 AuthenticationWebFilter 完成Oauth2.0的token校驗。

AuthenticationWebFilter 通過我們自定義的 ReactiveJdbcAuthenticationManager 完成token校驗。

6. 搭建授權認證中心

SpringCloudAliaba 基于OAth2.0 搭建認證授權中心

二、搭建產品服務
2.1. 創建boot項目

模塊名稱product-serv

2.2. 引入依賴
<parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.3.2.RELEASE</version><relativePath/> <!-- lookup parent from repository --></parent><groupId>com.gblfy</groupId><artifactId>product-serv</artifactId><version>1.0-SNAPSHOT</version><!--https://github.com/alibaba/spring-cloud-alibaba/wiki/%E7%89%88%E6%9C%AC%E8%AF%B4%E6%98%8E--><properties><java.version>1.8</java.version><spring.cloud-version>Hoxton.SR9</spring.cloud-version></properties><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><!--服務注冊發現--><dependency><groupId>com.alibaba.cloud</groupId><artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId></dependency></dependencies><dependencyManagement><dependencies><!--spring-cloud 版本控制--><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-dependencies</artifactId><version>${spring.cloud-version}</version><type>pom</type><scope>import</scope></dependency><!--spring-cloud-alibaba 版本控制--><dependency><groupId>com.alibaba.cloud</groupId><artifactId>spring-cloud-alibaba-dependencies</artifactId><version>2.2.6.RELEASE</version><type>pom</type><scope>import</scope></dependency></dependencies></dependencyManagement>
2.3. controller
package com.gblfy.controller;import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RestController;@RestController public class ProductController {//http://localhost:9000/product/" + productId@GetMapping("/product/{productId}")public String getProductName(@PathVariable Integer productId) {return "IPhone 12";} }
2.4. 啟動類
package com.gblfy;import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplication public class ProductAplication {public static void main(String[] args) {SpringApplication.run(ProductAplication.class);} }
2.5. 配置
server:port: 9000 spring:cloud:nacos:discovery:service: product-servserver-addr: localhost:8848
四、測試驗證
4.1. 啟動nacos

4.2. 啟動認證中心

4.3. 啟動產品服務

4.3. 請求認證授權中心

不攜帶token

4.4. 網關請求產品模塊

通過網關請求產品服務,提示需要認證

4.5. 獲取token

http://localhost:8081/oauth/token
通過認證授權中心獲取toekn

grant_type:password client_id:app client_secret:app username:ziya password:111111


發起請求,獲取token

4.6. 攜帶token請求產品服務

http://product.gblfy.com:8081/product/1

Authorization:Bearer d364c6cc-3c60-402f-b3d0-af69f6d6b73e

4.7. 直接請求產品服務

4.8. 請求結果比對

從4.6和4.7可以看出,當從授權中心獲取token,攜帶token通過網關服務請求產品服務和直接請求產品服務效果是一樣的。

五、總結

從以上測試結果可以看出gateway已經啟動了一個統一認證授權的作用,對獲取的token進行校驗。以前我們所有的模塊都需要集成認證授權模塊,現在呢?所有的流量都從微服務網關SpringCloud Gateway走,那認證授權也是通過gateway來做的。因此,只需要在網關集成認證授權模塊,其他的都不需要集成和配置。

總結

以上是生活随笔為你收集整理的SpringCloud Gateway 集成 oauth2 实现统一认证授权_03的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。

主站蜘蛛池模板: 成人午夜免费观看 | 浪漫樱花动漫在线观看免费 | 一区二区三区丝袜 | 国产农村老头老太视频 | 午夜国产片 | 中文字幕在线免费 | 亚洲成人免费看 | 在线观看麻豆视频 | 欧美激情精品久久久久久 | 日本在线免费 | 黄色91在线观看 | 激情噜噜| 亚洲五月网 | 日本一区精品视频 | www.狠狠爱| 色婷婷一区二区 | 一级做a爰片毛片 | 亚洲欧洲精品在线 | 成人图片小说 | jizz免费视频 | 精品国产伦一区二区三 | 日韩成人黄色片 | 91视频在线观看网站 | 黄色岛国片| 在线视频中文字幕 | 在线不卡免费av | 日产精品久久久久久久蜜臀 | 97免费在线视频 | 亚洲资源在线观看 | 久久久国产精品视频 | 国产婷婷综合 | 熟女毛毛多熟妇人妻aⅴ在线毛片 | 午夜电影天堂 | 天天干夜夜干 | 日本色综合网 | 中文av一区二区 | 精品产国自在拍 | 女久久| 欧美浪妇xxxx高跟鞋交 | 精品久久久久中文慕人妻 | 激情五月综合网 | 色狠狠综合网 | 樱桃av| 97精品人妻一区二区三区香蕉 | 日韩成人在线视频观看 | 成人av播放 | 国产精品久久久久久久久久久久久久久 | 禁欲天堂 | 午夜天堂影院 | 天堂俺去俺来也www久久婷婷 | 1024精品一区二区三区日韩 | 国产精品无码内射 | 色小说在线观看 | 国产亚洲一区二区三区不卡 | 国产大学生自拍视频 | www.久久精品 | 成人一区二区电影 | 欧美激情五月 | 亚洲国产精选 | 超碰在线进入 | 天天色棕合合合合合合合 | 日韩成人在线免费观看 | 大地资源高清播放在线观看 | 国产xxxx裸体xxx免费 | 国产精品自产拍高潮在线观看 | 国产传媒在线播放 | 中文成人在线 | 国产日韩精品一区二区三区 | 手机天堂av | 比利时xxxx性hd极品 | 亚洲国产精品一区二区尤物区 | 日韩日日日 | 免费毛片基地 | 色戒电影未测减除版 | 自拍偷拍第2页 | 在线欧美激情 | 青青草公开视频 | 日韩精选av | 天堂中文字幕在线 | 亚洲中午字幕 | 熟妇人妻av无码一区二区三区 | 制服丝袜av一区二区三区下载 | 18p在线观看 | 人妖粗暴刺激videos呻吟 | 夜夜嗨aⅴ一区二区三区 | 中文字幕av在线免费 | free国产hd露脸性开放 | 男人天堂你懂的 | 黄色免费小视频 | 国产视频精品在线 | av在线不卡一区 | 精品欧美一区二区三区久久久 | 国产三级播放 | 啪啪一区二区 | 狠狠操夜夜爽 | 国产农村老头老太视频 | 99人妻碰碰碰久久久久禁片 | 91精品婷婷国产综合久久蝌蚪 | 麻豆传媒在线视频 |