文章目录
最近在研究一个开源的后台管理系统 RuoYi
,对于里面使用的 SpringSecurity
,以前没用过,下面来学习一下。
RuoYi
官网:https://doc.ruoyi.vip
1. 新建项目
新建Spring Boot
项目,先引入web
依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
项目创建成功后,添加一个测试的 IndexController
,内容如下
@RestController
public class IndexController {
@RequestMapping("/index")
public String index(){
return "hello index";
}
}
接下直接来启动项目,在浏览器中访问:http://localhost:8080/index
,发现是可以任意访问的。
好了,下面来引入Spring Security
依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
重新启动项目,再访问http://localhost:8080/index
,发现跳转到下面这个登录页面了。没错,这就加入了权限校验。
那这个用户名和密码是什么呢?查看下项目启动过程日志,会看到如下一行日志:
Using generated security password: 210b9d32-323e-4467-bf26-e0563a3c3c34
这就是Spring Security
为默认用户user
生成的临时密码,是一个 UUID
字符串。
输入用户名密码,登录成功后,就可以访问到 /index
接口。
在
Spring Security
中,默认的登录页面和登录接口,都是/login
,只不过一个是get
请求(登录页面),另一个是post
请求(登录接口)
可以看到,引入SpringSecurity
依赖就可以保护了所有接口,很方便!!!
对于上面默认的用户名和随机生成的临时密码,看下源码。和用户相关的自动化配置类UserDetailsServiceAutoConfiguration
在控制台看到的日志就是这里打印出来的。打印的条件是 isPasswordGenerated()
方法返回 true
,即密码是默认生成的。
点击查看user.isPasswordGenerated()
方法,发现会进入到 SecurityProperties
中,在