搭建簡單的基於spring security的spring cloud框架 遇到的問題詳解
先給出pom檔案:
主pom.xml:
<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.best800</groupId> <artifactId>demo-springcloud</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>pom</packaging> <name>demo-springcloud</name> <description>Demo project for Spring Boot</description> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.0.3.RELEASE</version> <relativePath/> </parent> <modules> <module>eureka-server</module> <module>demo-login</module> </modules> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <java.version>1.8</java.version> <spring-cloud.version>Finchley.RELEASE</spring-cloud.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> <dependencyManagement> <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> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
demo-login的pom.xml:
<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.best800</groupId> <artifactId>demo-login</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>demo-login</name> <description>Demo project for Spring Boot</description> <parent> <groupId>com.best800</groupId> <artifactId>demo-springcloud</artifactId> <version>0.0.1-SNAPSHOT</version> </parent> <dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!--Swagger測試文件--> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.7.0</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.7.0</version> </dependency> <!-- spring security依賴 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.46</version> </dependency> <dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-redis</artifactId> <version>2.1.3.RELEASE</version> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.16.18</version> </dependency> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatisplus-spring-boot-starter</artifactId> <version>3.0-alpha</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-extension</artifactId> <version>3.0-alpha</version> </dependency> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.3.1</version> </dependency> </dependencies> <build> <resources> <resource> <directory>src/main/resources</directory> <filtering>true</filtering> </resource> </resources> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> <plugin> <artifactId>maven-compiler-plugin</artifactId> <version>3.8.0</version> </plugin> </plugins> <!--<resources>--> <!--<resource>--> <!--<directory>src/main/resources</directory>--> <!--<!– 此配置不可缺,否則mybatis的Mapper.xml將會丟失 –>--> <!--<includes>--> <!--<include>**/*.xml</include>--> <!--<include>**/*.html</include>--> <!--</includes>--> <!--</resource>--> <!--<!–指定資源的位置–>--> <!--<resource>--> <!--<directory>src/main/resources</directory>--> <!--<includes>--> <!--<include>*.yml</include>--> <!--<include>*.properties</include>--> <!--</includes>--> <!--</resource>--> <!--</resources>--> </build> </project>
設計的資料庫表結構:
專案結構:
SecurityConf:
package com.best800.demologin.conf; import com.best800.demologin.MyAuthenticationFailHander; import com.best800.demologin.MyAuthenticationSuccessHandler; import com.best800.demologin.service.MyAuthenticationProvider; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import org.springframework.http.HttpMethod; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired MyAuthenticationProvider myAuthenticationProvider; @Autowired MyAuthenticationSuccessHandler myAuthenticationSuccessHandler; @Autowired MyAuthenticationFailHander myAuthenticationFailHander; @Override protected void configure(HttpSecurity http) throws Exception { // // TODO Auto-generated method stub // //表單登入,permitAll()表示這個不需要驗證 登入頁面,登入失敗頁面 //// http //// .formLogin().loginPage("/login").loginProcessingUrl("/login").failureUrl("/login-error").permitAll() //// .and() //// .authorizeRequests() //// .antMatchers("/v2/api-docs", "/configuration/ui", "/swagger-resources", "/configuration/security", "/swagger-ui.html", "/webjars/**", "/swagger-resources/configuration/ui", "/swagger-ui.html").permitAll() //// .anyRequest().authenticated() //// .and() //// .csrf().disable(); //// } http .formLogin().loginPage("/login").loginProcessingUrl("/login/form").failureUrl("/login-error").permitAll() //表單登入,permitAll()表示這個不需要驗證 登入頁面,登入失敗頁面 .successHandler(myAuthenticationSuccessHandler) .failureHandler(myAuthenticationFailHander) .and() .authorizeRequests().anyRequest().authenticated() .and() .authorizeRequests() .antMatchers("/hello").permitAll() .antMatchers(HttpMethod.GET,"/whoim").hasRole("ADMIN") // .anyRequest().access("@rbacService.hasPermission(request,authentication)") .and() .csrf().disable(); } } // @Autowired // public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { // // auth.authenticationProvider(myAuthenticationProvider); //// auth.inMemoryAuthentication() //// .withUser("admin").password("123456").roles("USER"); // } //}
接下來一些簡單配置自己百度就好 程式碼最好自己實現
主要說下遇到的價格問題:
1.
***************************
APPLICATION FAILED TO START
***************************
Description:
Failed to auto-configure a DataSource: 'spring.datasource.url' is not specified and no embedded datasource could be auto-configured.
Reason: Failed to determine a suitable driver class
Action:
Consider the following:
If you want an embedded database (H2, HSQL or Derby), please put it on the classpath.
If you have database settings to be loaded from a particular profile you may need to activate it (no profiles are currently active).
Mybatis沒配置好資料庫環境原因 在你的yml寫下:
spring:
datasource:
username: root
password: 123456
url: jdbc:mysql://127.0.0.1:3306/test?
characterEncoding=utf8&useSSL=false&autoReconnect=true
driver-class-name: com.mysql.jdbc.Driver
mybatis:
mapper-locations: classpath:mapper/*Mapper.xml
type-aliases-package: com.best800.demologin.model.dto
2.swagger只顯示樣式 但是不具體顯示介面
很蠢的答案 包名 可能使從網上覆制的答案但是包名沒改過來
3.swagger頁面報錯404或者
Unable to infer base url. This is common when using dynamic servlet registration or when the API is behind an API Gateway. The base url is the root of where all the swagger resources are served. For e.g. if the api is available at http://example.org/api/v2/api-docs then the base url is http://example.org/api/. Please enter the location manually:
jar包版本問題 按照上述demo-login的版本即可
4.mybatis-plus 按照配置檔案找不到相應的dao層和xml檔案
jar包問題 mybatis-plus-boot-starter 和 mybatisplus-spring-boot-starter
5.springboot中的web專案不能訪問templates中的靜態資源
如果配置檔案中的相關配置沒有寫錯 可能是 在controller裡 用了@RestController註解
@RestController = @Controller + @ResponseBody 返回的json 所以在controller的返回"index.html"裡 返回的永遠是String
6.idea裡提示資料庫連線時間超時 可能是配置的資訊有問題 輕易不要改my.ini檔案
如果改了 報錯 mysql處於啟動卡死的狀態 要先用管理員身份開啟cmd 使用命令 skilltask殺死相應的程序
在進入mysql 的目錄 重新啟動一個cmd 執行mysql啟動
7. 如果jar包匯入不成功,可以嘗試下mvn install 和mvn package
最後推薦幾個比較有用的配件
codeglance程式碼的縮圖 可以看做是LOL的小地圖
sequence diagram 右鍵方法 自動生成uml圖 方便讀懂別人程式碼
mybatis plugin 不用多說
String manipulation 快速修改駝峰命名
最後還是貼一下 配置檔案吧:
server:
port: 9001
eureka:
client:
service-url:
defaultZone: http://localhost:8080/eureka
spring:
application:
name: demo-login
resources:
static-locations: classpath:/templates/
datasource:
username: root
password: 123456
url: jdbc:mysql://127.0.0.1:3306/test?characterEncoding=utf8&useSSL=false&autoReconnect=true
driver-class-name: com.mysql.jdbc.Driver
# redis:
# host: 127.0.0.1
# password: redispassword
# port: 6379
# jedis:
# pool:
# min-idle: 0
# max-active: 8
# max-idle: 8
# database: 0
thymeleaf:
prefix: classpath:/templates/
mode: HTML5
suffix: .html
#mybatis
mybatis-plus:
mapper-locations: classpath:mapper/*Mapper.xml
#實體掃描,多個package用逗號或者分號分隔
typeAliasesPackage: com.best800.demologin.model.dto
# typeEnumsPackage: cnzsqh.supplychain.*.po.enums
global-config:
#重新整理mapper 除錯神器
db-config:
#主鍵型別 0:"資料庫ID自增", 1:"使用者輸入ID",2:"全域性唯一ID (數字型別唯一ID)", 3:"全域性唯一ID UUID";
id-type: auto
#欄位策略 0:"忽略判斷",1:"非 NULL 判斷"),2:"非空判斷"
field-strategy: not_empty
#駝峰下劃線轉換
column-underline: true
#資料庫大寫下劃線轉換
#capital-mode: true
#邏輯刪除配置
logic-delete-value: 0
logic-not-delete-value: 1
db-type: h2
refresh: true
#自定義填充策略介面實現
#meta-object-handler: com.baomidou.springboot.xxx
#自定義SQL注入器
#sql-injector: com.baomidou.springboot.xxx
configuration:
map-underscore-to-camel-case: true
cache-enabled: false
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
logging:
level:
com:
ibatis: debug
mybatis:
mapper-locations: classpath:mapper/*Mapper.xml
type-aliases-package: com.best800.demologin.model.dto