目錄
1.技術棧:
2.模塊介紹:
3.關鍵代碼講解
3.1基礎公共模塊(common)依賴:
3.3授權模塊(auth)依賴:
3.4授權模塊核心配置類(AuthrizatonConfig):
3.4? SecurityConfig.java
?3.5 bootstrap的核心配置文件(其他服務配置類似這個):
3.6nacos上面的配置文件如auth-dev.yaml
3.7 consumer-dev.yaml
3.8 gateway-dev.yaml:
3.9mq-dev.yaml:
4.授權認證模塊演示:
4.1獲取到授權碼:
4.2 通過postman請求獲取access_token
4.2測試通過access_token訪問資源:
4.3 無token攜帶的時候,訪問服務資源
4.4 在指定模塊添加配置類(ResourceServerConfig):
5.nacos相關配置,以及服務注冊情況
5.1nacos配置顯示:
5.2 nacos上服務顯示:
1.技術棧:
SpringCloud? 微服務基礎架構
1.1.nacos? 用于服務的注冊,作為注冊中心,同時也利用了nacos的熱更新特點,使用nacos作為配置中心。
1.2.Mysql 主要用了mqsql8.0版本,mysql作為關系型數據庫的存儲
1.3.MybatisPlus 主要使用了MybatisPlu實現對mysql數據庫的操作,實現增刪改查。
1.4.Oauth2.0 主要使用ouath2.0實現微服務的授權認證登錄。
1.5.消息隊列 rabbitMQ,應對物聯網設備數據并發的中間件,對設備數據進行排隊處理
1.6.emqx 主要用于設備的mqtt連接
2.模塊介紹:
2.1.auth模塊:主要是集成了數據庫的連接,以及ouath 的授權認證功能。
2.2.common模塊:作為公共模塊,為其他模塊提供基礎類以及公共依賴,降低代碼的耦合度
2.3.consumer模塊:消費者模塊,主要用于消費rabbitmq產生的數據信息。
2.4.mq模塊:主要用于設備處理設備上報的數據。
2.5.gateway模塊:主要作為接口請求統一入口,做鏈路追蹤,以及攔截請求。
2.6.system模塊:后臺管理平臺業務開發模塊。
代碼結構示意圖:
3.關鍵代碼講解
3.1基礎公共模塊(common)依賴:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.3.2.RELEASE</version><!-- lookup parent from repository --></parent><groupId>com.example</groupId><artifactId>common</artifactId><version>0.0.1-SNAPSHOT</version><name>common</name><description>Demo project for Spring Boot</description><url/><licenses><license/></licenses><developers><developer/></developers><scm><connection/><developerConnection/><tag/><url/></scm><properties><java.version>8</java.version></properties><dependencies><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-dependencies</artifactId><version>Hoxton.SR8</version><type>pom</type><scope>import</scope></dependency><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-bootstrap</artifactId><version>3.0.0</version></dependency><dependency><groupId>com.alibaba.cloud</groupId><artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId><version>2.2.5.RELEASE</version></dependency><dependency><groupId>com.alibaba.cloud</groupId><artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId><version>2.2.5.RELEASE</version></dependency><!-- mybatis-plus --><dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-boot-starter</artifactId><version>3.4.2</version></dependency><!-- mysql --><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId></dependency><!-- lombok --><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><optional>true</optional></dependency><!--阿里巴巴數據庫連接池--><dependency><groupId>com.alibaba</groupId><artifactId>druid-spring-boot-starter</artifactId><version>1.2.8</version></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-aop</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency></dependencies><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin></plugins></build></project>
3.2網關相關依賴:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.3.2.RELEASE</version><!-- lookup parent from repository --></parent><groupId>com.example</groupId><artifactId>gateway</artifactId><version>0.0.1-SNAPSHOT</version><name>gateway</name><description>Demo project for Spring Boot</description><url/><licenses><license/></licenses><developers><developer/></developers><scm><connection/><developerConnection/><tag/><url/></scm><properties><java.version>8</java.version></properties><dependencies><dependency><groupId>com.example</groupId><artifactId>common</artifactId><version>0.0.1-SNAPSHOT</version><exclusions><exclusion><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></exclusion></exclusions></dependency><!-- 網關配置--><!--網關發現服務后,進行負載均衡的轉發調用--><!-- <dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-loadbalancer</artifactId><version>3.1.2</version></dependency>--><!--網關核心依賴--><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-gateway</artifactId><version>2.2.10.RELEASE</version><exclusions><exclusion><groupId>io.projectreactor.netty</groupId><artifactId>reactor-netty</artifactId></exclusion></exclusions></dependency><!--版本沖突報錯指定reactor-netty、spring-webflux版本--><dependency><groupId>org.springframework</groupId><artifactId>spring-webflux</artifactId><version>5.2.7.RELEASE</version></dependency><dependency><groupId>io.projectreactor.netty</groupId><artifactId>reactor-netty</artifactId><version>0.9.14.RELEASE</version></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency></dependencies><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin></plugins></build></project>
3.3授權模塊(auth)依賴:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.3.2.RELEASE</version><!-- lookup parent from repository --></parent><groupId>com.example</groupId><artifactId>auth</artifactId><version>0.0.1-SNAPSHOT</version><name>auth</name><description>Demo project for Spring Boot</description><url/><licenses><license/></licenses><developers><developer/></developers><scm><connection/><developerConnection/><tag/><url/></scm><properties><java.version>8</java.version></properties><dependencies><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId></dependency><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-oauth2</artifactId><version>2.2.5.RELEASE</version></dependency><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-security</artifactId><version>2.2.5.RELEASE</version></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-actuator</artifactId></dependency><!-- 引入公共模塊--><dependency><groupId>com.example</groupId><artifactId>common</artifactId><version>0.0.1-SNAPSHOT</version></dependency><!--引入數據庫模塊--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency></dependencies><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin></plugins></build></project>
3.4授權模塊核心配置類(AuthrizatonConfig):
package com.example.auth.config;import org.apache.http.protocol.HTTP;
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.AuthenticationManager;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.code.AuthorizationCodeServices;
import org.springframework.security.oauth2.provider.code.InMemoryAuthorizationCodeServices;
import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;
import org.springframework.security.oauth2.provider.token.DefaultTokenServices;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.InMemoryTokenStore;
//訪問授權地址獲取授權碼 http://localhost:8063/oauth/authorize?client_id=test&response_type=code&scope=all&redirect_uri=http://www.baidu.com
@Configuration
@EnableAuthorizationServer
public class AuthrizatonConfig extends AuthorizationServerConfigurerAdapter {@Autowiredprivate ClientDetailsService clientDetailsService;@Autowiredprivate AuthenticationManager authenticationManager;@Overridepublic void configure(AuthorizationServerSecurityConfigurer security) throws Exception {security//開啟tokenkey權限訪問.tokenKeyAccess("permitAll()").checkTokenAccess("permitAll()").allowFormAuthenticationForClients();}@Overridepublic void configure(ClientDetailsServiceConfigurer clients) throws Exception {clients.inMemory().withClient("test").secret(new BCryptPasswordEncoder().encode("123456")).resourceIds("auth","mq","gateway").authorizedGrantTypes("authorization_code","password","client_credentials","implicit","refresh_token").scopes("all").autoApprove(false).redirectUris("http://www.baidu.com");}/*** 令牌存儲策略* @return*/@Beanpublic TokenStore tokenStore(){return new InMemoryTokenStore();}@Beanpublic AuthorizationServerTokenServices tokenServices(){DefaultTokenServices services = new DefaultTokenServices();services.setSupportRefreshToken(true);services.setTokenStore(tokenStore());services.setAccessTokenValiditySeconds(60*60*60*2);services.setRefreshTokenValiditySeconds(60*60*24*3);return services;}public AuthorizationCodeServices authorizationCodeServices(){return new InMemoryAuthorizationCodeServices();}@Overridepublic void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {endpoints.authorizationCodeServices(authorizationCodeServices()).authenticationManager(authenticationManager).tokenServices(tokenServices()).allowedTokenEndpointRequestMethods(HttpMethod.POST);}
}
3.4? SecurityConfig.java
package com.example.auth.config;import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {/*** 密碼加密* @return*/@BeanPasswordEncoder passwordEncoder(){return new BCryptPasswordEncoder();}@Overrideprotected void configure(AuthenticationManagerBuilder auth) throws Exception {auth.inMemoryAuthentication().withUser("admin").password(new BCryptPasswordEncoder().encode("123456")).roles("admin");}@Overrideprotected void configure(HttpSecurity http) throws Exception {//允許表單登錄http.authorizeRequests().anyRequest().authenticated().and().formLogin().loginProcessingUrl("/login").permitAll().and().csrf().disable();}@Override@Beanpublic AuthenticationManager authenticationManagerBean() throws Exception {return super.authenticationManagerBean();}
}
?3.5 bootstrap的核心配置文件(其他服務配置類似這個):
server:port: 8061
spring:application:name: authprofiles:active:devcloud:nacos:config:file-extension: yaml#啟用配置熱更新功能refresh-enabled: trueprefix: authserver-addr: 192.168.1.24:8848discovery:instance-enabled: trueserver-addr: 192.168.1.24:8848cluster-name: authservice: auth-service
3.6nacos上面的配置文件如auth-dev.yaml
spring:datasource:driver-class-name: com.mysql.cj.jdbc.Driverurl: jdbc:mysql://localhost:3306/auth?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf-8&allowMultiQueries=true&nullCatalogMeansCurrent=trueusername: rootpassword: Root@123type: com.alibaba.druid.pool.DruidDataSourcedruid:initial-size: 5min-idle: 1max-active: 10max-wait: 60000validation-query: SELECT 1 FROM DUALtest-on-borrow: falsetest-on-return: falsetest-while-idle: truetime-between-eviction-runs-millis: 60000
mysql:driver: com.mysql.jdbc.driver
3.7 consumer-dev.yaml
spring:datasource:driver-class-name: com.mysql.cj.jdbc.Driverurl: jdbc:mysql://localhost:3306/auth?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf-8&allowMultiQueries=true&nullCatalogMeansCurrent=trueusername: rootpassword: Root@123type: com.alibaba.druid.pool.DruidDataSourcedruid:initial-size: 5min-idle: 1max-active: 10max-wait: 60000validation-query: SELECT 1 FROM DUALtest-on-borrow: falsetest-on-return: falsetest-while-idle: truetime-between-eviction-runs-millis: 60000
3.8 gateway-dev.yaml:
spring:datasource:driver-class-name: com.mysql.cj.jdbc.Driverurl: jdbc:mysql://localhost:3306/gateway?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf-8&allowMultiQueries=true&nullCatalogMeansCurrent=trueusername: rootpassword: Root@123type: com.alibaba.druid.pool.DruidDataSourcedruid:initial-size: 5min-idle: 1max-active: 10max-wait: 60000validation-query: SELECT 1 FROM DUALtest-on-borrow: falsetest-on-return: falsetest-while-idle: truetime-between-eviction-runs-millis: 60000cloud:gateway:globalcors: # 全局的跨域配置# 解決options請求被攔截問題add-to-simple-url-handler-mapping: true # options請求 就是一種詢問服務器是否瀏覽器可以跨域的請求# 如果每次跨域都有詢問服務器是否瀏覽器可以跨域對性能也是損耗# 可以配置本次跨域檢測的有效期maxAge# 在maxAge設置的時間范圍內,不去詢問,統統允許跨域corsConfigurations:'[/**]':allowedOrigins: # 允許哪些網站的跨域請求 - "http://localhost:8061"allowedMethods: # 允許的跨域ajax的請求方式- "GET"- "POST"- "DELETE"- "PUT"- "OPTIONS"allowedHeaders: "*" # 允許在請求中攜帶的頭信息allowCredentials: true # 允許在請求中攜帶cookiemaxAge: 360000 # 本次跨域檢測的有效期(單位毫秒)discovery:locator:enabled: trueroutes:#路由微服務名稱,- id: auth-service #路由目標微服務 lb代表負載均衡協議uri: lb://auth-service #以請求路徑做判斷,只要符合匹配規則的請求就會被轉發到上面信息對應的微服務中去 #路由斷言,判斷是否符合規則,符合規則路由到目標 predicates: - Path=/auth/**,/search/** - id: consumer-serviceuri: lb://consumer-servicepredicates:- Path=/consumer/**- id: system-serviceuri: lb://system-servicepredicates:- Path=/system/**,/addresses/**- id: mq-serviceuri: lb://mq-servicepredicates:- Path=/mq/**#filters: # 過濾器,請求在傳遞過程中可以通過過濾器對其進行一定的修改# 轉發之前去掉1層路徑#- StripPrefix=1 default-filters: #默認過濾器,對請求進行處理#在請求頭中添加信息,前鍵后值。- AddRequestHeader=headerName, project is well
3.9mq-dev.yaml:
mq: dsswaz
spring:datasource:driver-class-name: com.mysql.cj.jdbc.Driverurl: jdbc:mysql://localhost:3306/auth?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf-8&allowMultiQueries=true&nullCatalogMeansCurrent=trueusername: rootpassword: Root@123type: com.alibaba.druid.pool.DruidDataSourcedruid:initial-size: 5min-idle: 1max-active: 10max-wait: 60000validation-query: SELECT 1 FROM DUALtest-on-borrow: falsetest-on-return: falsetest-while-idle: truetime-between-eviction-runs-millis: 60000
4.授權認證模塊演示:
通過訪問http://localhost:8061/oauth/authorize?client_id=test&response_type=code&scope=all&redirect_uri=http://www.baidu.com
地址獲取code? 輸入賬戶 admin? 密碼:123456
4.1獲取到授權碼:
4.2 通過postman請求獲取access_token
4.2測試通過access_token訪問資源:
4.3 無token攜帶的時候,訪問服務資源
4.4 在指定模塊添加配置類(ResourceServerConfig):
package com.example.mq.config;import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.RemoteTokenServices;@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {@Beanpublic RemoteTokenServices tokenServices(){RemoteTokenServices tokenServices = new RemoteTokenServices();tokenServices.setCheckTokenEndpointUrl("http://localhost:8061/oauth/check_token");tokenServices.setClientId("test");tokenServices.setClientSecret("123456");return tokenServices;}@Overridepublic void configure(ResourceServerSecurityConfigurer resources) throws Exception {resources.resourceId("mq").tokenServices(tokenServices());}@Overridepublic void configure(HttpSecurity http) throws Exception {http.authorizeRequests().antMatchers("/**").access("#oauth2.hasScope('all')").anyRequest().authenticated();}
}
5.nacos相關配置,以及服務注冊情況
5.1nacos配置顯示:
5.2 nacos上服務顯示:
通過以上配置完成微服務框架的簡單auth2.0授權配置。