项目源码地址 https://github.com/nieandsun/security
1. 项目搭建关键步骤(开发工具为idea,项目为springboot项目)
①新建项目时要选上如下两个依赖
②项目创建完成后的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>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.5.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.nrsc</groupId>
<artifactId>security</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>security</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</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-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-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>
2. Spring-Security默认行为演示
①创建一个简单的Controller,项目目录结构如下
②启动项目,访问localhost:8080/hello结果如下
③上面的Username是固定的为user,Password可在项目启动日志里找到
④输入用户名和密码后就可以访问到期望访问的资源了,访问内容如下
3.简单修改Spring-Security的默认行为
- 创建一个类继承WebSecurityConfigurerAdapter类,springboot在启动时会去看是否有WebSecurityConfigurerAdapter类的继承类,如果有的话,将按照该类中指定的方式来确定spring-security的作用行为
①创建SecurityConfig类继承WebSecurityConfigurerAdapter,这里仅仅修改spring-security的认证方式,代码及相关解释如下
②重新启动项目,访问localhost:8080/hello结果如下
可以看到项目的登陆方式已经发生了改变