SpringSecurity快速入门(QuickStart)
文末有本篇文章的项目源码文件可供下载学习
SpringSecurity是一个用于在Java应用程序中实现认证和授权的框架,它提供了一套功能强大且灵活的安全机制来保护应用程序中的资源。通过SpringSecurity,我们可以实现诸如用户认证、用户授权、访问控制等功能,从而保护应用程序免受恶意访问和攻击。
0.编程思路
- 搭建项目,配置pom.xml,主要引入SpringBoot2/web启动器/SpringSecurity5启动器
- 编写CustomerController.java文件,新建一个方法用于访问
- 多次访问测试,主要包括:未登录时,访问资源受限;登录上时,可以访问资源;要退出时,可以退出;退出后再访问资源时,再次受限;
1.配置pom.xml
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.5.15</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<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>
</dependencies>
2.编写CustomerController.java
@RestController
public class CustomerController {
@RequestMapping("securityTest")
public String firstMethod() {
return "这是自定义Controller的第一个方法,用于SpringSecurity测试";
}
}
3.访问测试
1.当我们将pom.xml文件中的SpringSecurity启动器注释掉的运行结果
<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>
</dependencies>
我们发现可以正常访问CustomerController的方法
2.当我们将pom.xml文件中的SpringSecurity启动器加入maven中时
<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>
</dependencies>
我们发现此处被限制访问了,并且将我们的访问地址重定向到localhost:8080/logn,并出现一个登录页面,这是SpringSecurity默认的登录页.这里需要我们输入Username和Password,Username默认为user,Password默认为项目启动时在控制台输出的密码,如下所示
我们将用户名和密码输入之后,如下所示:
我们发现URL变为了之前的localhost:8080/securityTest,并且在浏览器上显示了我们想要的内容.
当我们在浏览器访问locahost:8080/logout时,我们又跳转到了退出页面,如下所示:
当我们点击Log Out后,又返回到登录页面,如下所示:
此时我们再用浏览器访问localhost:8080/securityTest时,又跳转到登录页面,如下所示
此时我们就可以看出,SpringSecurity已经正常配置到我们的项目中了.
本篇文章的项目源码文件,可供下载学习