搭建简单的基于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>-->
                <!--&lt;!&ndash; 此配置不可缺,否则mybatis的Mapper.xml将会丢失 &ndash;&gt;-->
                <!--<includes>-->
                    <!--<include>**/*.xml</include>-->
                    <!--<include>**/*.html</include>-->
                <!--</includes>-->
            <!--</resource>-->
            <!--&lt;!&ndash;指定资源的位置&ndash;&gt;-->
            <!--<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", "/swagge‌​r-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

猜你喜欢

转载自blog.csdn.net/qq_31310291/article/details/85600917