Spring Security

印象笔记:Spring Security
图片无法上传至,可以阅读上面的文章。

Spring Security

前言:
利用gradle工具来构建一个项目 springboot项目,同时利用Spring Security安全框架,来做权限安全验证。
在网上,看到更多的示例是关于maven项目+Spring boot+Spring Security的结合。索性自己写一个教程。
我希望你,能够在搭建项目之前了解以下内容:

  • Gradle构建工具
  • SpringBoot 的应用
  • Intellij IDEA 工具的使用

其中踩到不少坑,浪费了很多的时间来,解决这些问题。希望这篇文档能给你带来 帮助。

一、 创建一个Gradle项目

步骤:
[图片上传失败...(image-41962d-1534468591386)]
[图片上传失败...(image-3b2ef3-1534468591387)]
[图片上传失败...(image-b53c71-1534468591387)]
然后一路next,最终finally。
最终项目初始结构:

[图片上传失败...(image-53b0e8-1534468591387)]
注意:Idea创建gradle项目,不能够自动创建src源码包,需要自己手动创建。
我在这里写了两个任务,放到build.gradle中执行,可以自动创建src,test包。


def creatDir={
path ->
File dir =new File(path);
if(!dir.exists()){
dir.mkdirs();
}
}

task makeJavaDir() {
def paths = ['src/main/java', 'src/main/resources', 'src/test/java', 'src/test/resources'];
// 在创建任务之前 先遍历 路径
doFirst {
paths.forEach(creatDir);
}
}

// web 项目目录结构 包含了java项目目录结构
task makeWebDir(){
dependsOn 'makeJavaDir';
def paths=['src/main/webapp','src/test/webapp'];
doLast {
paths.forEach(creatDir)
}
}


在Tasks-->other中便能找到这两个任务,选中执行即可。
[图片上传失败...(image-f7d83b-1534468591387)]

运行完之后的项目结构:
[图片上传失败...(image-bfab13-1534468591387)]

再次刷新 依赖导入,如下图效果,即搭建gradle项目成功了。
[图片上传失败...(image-53bfcb-1534468591387)]


二、启动一个springBoot 项目

1、重写 build.gradle文件
主要是配置项目的信息。
buildscript中配置都是gradle自身的配置。


buildscript {
     ext {
        springBootVersion = '2.0.3.RELEASE'
        projectJdk = '1.8'
        projectGroup = 'com.security'
        projectVersion = '0.0.1'
        projectName = 'securitydemo'
        // 注意 mavenUrl一行  可以省略
        mavenUrl =  "http://192.168.0.14/nexus/repository/maven-public/";
    }
    repositories {
        mavenLocal()
         // 注意 maven 一行 可以省略
        maven { url = mavenUrl }
        mavenCentral();
    }
    dependencies {
        classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
    }
}
// 以下配置为项目的自身配置
apply plugin: 'java'
apply plugin: 'idea'
apply plugin: 'war'
apply plugin: 'org.springframework.boot'
apply plugin: 'io.spring.dependency-management'
apply plugin: 'maven-publish'

group = projectGroup
version = projectVersion
sourceCompatibility = projectJdk
repositories {
    mavenLocal()
      // 注意 maven 一行 可以省略  ,换为   mavenCentral();
    maven { url = mavenUrl }
}
dependencies {
    compile('org.springframework.boot:spring-boot-starter-web')
    compile('org.springframework.boot:spring-boot-starter-aop')
    compile("org.apache.tomcat.embed:tomcat-embed-jasper")
    compile('org.springframework.boot:spring-boot-starter-thymeleaf')
    testCompile('org.springframework.boot:spring-boot-starter-test')
    // spring-security 依赖 暂时注释掉
//    compile('org.springframework.boot:spring-boot-starter-security')

 //   compile group: 'org.thymeleaf.extras', name: 'thymeleaf-extras-springsecurity4', version: '3.0.2.RELEASE'

    compile('com.alibaba:druid-spring-boot-starter:1.1.10')
    compile("org.mybatis.spring.boot:mybatis-spring-boot-starter:1.3.2")
    compile("mysql:mysql-connector-java:8.0.11")
    compile("com.github.pagehelper:pagehelper-spring-boot-starter:1.2.5")
    compile("org.springframework.boot:spring-boot-devtools")
    compile("tk.mybatis:mapper-spring-boot-starter:2.0.3")
    compile("org.mybatis.generator:mybatis-generator-core:1.3.7")

    compile group: 'commons-lang', name: 'commons-lang', version: '2.6'
    compile group: 'commons-beanutils', name: 'commons-beanutils', version: '1.9.3'
    compile group: 'com.google.code.gson', name: 'gson', version: '2.8.5'
    compile 'com.github.joschi.jackson:jackson-datatype-threetenbp:2.6.4'

    compile group: 'org.apache.httpcomponents', name: 'httpclient', version: '4.5.6'


    compile ('org.springframework.social:spring-social-web:1.1.0.RELEASE')
}

2、创建com.security包,并在包下创建SpringBootApplcationDemo类。
之后便启动这个类。
[图片上传失败...(image-897292-1534468591387)]

**清单一 **:创建SpringBootApplcationDemo

@SpringBootApplication
public class SpringBootApplicationDemo {
    public static void main(String[] args) {
        SpringApplication.run(SpringBootApplicationDemo.class,args);
    }
}

3、在com.security包下创建controller包,并在其下,创建HelloController类。

清单二:创建HelloController


@RestController
public class HelloController {
    @GetMapping("/")
    public  String index(){
        return "Hello world!";
    }
}

4、 启动SpringBootApplcationDemo类,浏览器中输入:localhost:8080/,看到Hello world!便搭建springboot+gradle成功了。

[图片上传失败...(image-12ad3-1534468591387)]


三、 结合SpirngSecurity 做一个安全登录

1、在build.gradle中导入Spring Security相关依赖。

注意是在项目中的dependencies中导入下面的依赖,不是在buildscript中的dependencies中导入

清单三:导入依赖spring-security:5.0.7.RELEAS 。


 // 导入spring security的依赖
    compile 'org.springframework.security:spring-security-web:5.0.7.RELEASE'
    compile 'org.springframework.security:spring-security-config:5.0.7.RELEASE'

可能会报,无法正确配置,无法解析jar包
[图片上传失败...(image-5bff8a-1534468591387)]

我实验后的结果是不好用的。于是便换了 依赖
清单四:spring security的依赖


    // 导入spring security的依赖
    compile('org.springframework.boot:spring-boot-starter-security')
    compile group: 'org.thymeleaf.extras', name: 'thymeleaf-extras-springsecurity4', version: '3.0.2.RELEASE'

这时候在导入依赖,编译能够成功。启动项目,访问localhost:8080/ 发现,被成功拦截了,显示的是spring-Security自带的登录界面。不在是第二大步springboot启动的结果 显示hello world!了。
[图片上传失败...(image-9ac96a-1534468591387)]

这时候便面临着一个登录问题,我们去控制台上会发现启动的时候生成了一串md5的密码
!springSecurity随机生成的密码](./1534386377356.png)。
这时候可以将密码输入,用户名随便输入。
我显示的结果为
[图片上传失败...(image-29a6e8-1534468591387)]

2、Web Security java配置及自定义登录密码

MyUserDetailsService 用来自定义用信息:设置密码,权限,账号状态等。
WebSecurityConfig 负责应用程序内的所有安全性(保护应用程序URL,验证提交的用户名和密码等等)
com.security包下创建conf包,再在其中分别创建MyUserDetailsService类和WebSecurityConfig类。

a) .创建 WebSecurityConfig类,来继承 WebSecurityConfigurerAdapter类。

在其中的类中 alt+insert 快捷键 导入父类的方法,进行重写。
[图片上传失败...(image-35985a-1534468591387)]
清单五:WebSecurityConfig

@EnableWebSecurity
public class WebSecurityConfig  extends WebSecurityConfigurerAdapter {
    // 覆盖默认的configure(HttpSecurity http) 配置
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.formLogin()
                .and()
                .authorizeRequests()
                .anyRequest()
                .authenticated();
    }

    // 密码 编码
    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }
}

b) .创建MyUserDetailsService类,来实现 UserDetailsService 接口。

清单六:MyUserDetailsService,定义用户基本信息。


@Component
public class MyUserDetailsService implements UserDetailsService {
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        String password=passwordEncoder.encode("123456");
        return new User(username,password,AuthorityUtils.commaSeparatedStringToAuthorityList("admin"));
    }
}

3、启动springboot 。在浏览器中变显示了登录界面。用户名随便输入,密码为123456 。登录成功变现实了Hello world!

[图片上传失败...(image-622cce-1534468591387)]
一个简单的springsecurity 示例,实验成功!

你可能感兴趣的:(Spring Security)