官网:https://spring.io/projects/spring-security
概述
一句话:如果你是使用spring框架开发项目,那么你可以考虑使用SpringSecurity框架来帮助你完成登录,权限,角色的控制。你再也不需要去开发登录相关功能,SpringSecurity会自动帮你完成。
SpringSecurity整体的架构体系
- 基于内存
- 基于数据库(90%)(rbac)
- 基于JWT (Filter + Aop)(rbac + jwt)
- 基于Auth2.0(基于token)
- 基于CAS机制
SpringSecurity核心基础
- **Authentication(认证) **
Authentication(认证) 的过程是用户通过密码登录系统,认证成功之后才能进入到系统,然后系统会为登录用户授权。授权的过程就是获取用户可操作的权限。之后当用户进行URL资源访问的时候,
- Authorization(授权)
系统会通过过滤器Filter 进行拦截,判断当前用户是否具有访问权限,
因为SpringSecurity框架的核心逻辑就是一系列的过滤器链。仅仅只是对资源请求的拦截,所以是一种粗粒度的权限验证,无法做到数据级别的权限控制。整个执行过程如下:
SpringSecurity安全框架的适配器(开发者做的事情)
开发者需要自己去创建自己的SpringSecurity的适配器类。然后继承WebSecurityConfigurerAdapter,然后用@Configuration标记即可。覆盖configure方法配置所需要的安全配置,如下:
@Configuration
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
// 认证
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
}
// 授权
@Override
protected void configure(HttpSecurity http) throws Exception {
}
}
SpringSecurity初始化默认机制
pom文件
<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>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
</dependencies>
启动主类
package com.pug.security;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
@SpringBootApplication
public class KuangstudyPugSecurityMemoryApplication {
public static void main(String[] args) {
SpringApplication.run(KuangstudyPugSecurityMemoryApplication.class, args);
}
}
启动以后会生成一个默认用户:“user” 的密码如下:
Using generated security password: 7ada54d0-5086-4af3-87c3-8db221a35cc8
、访问
http://localhost:8080/login
把“user”和密码填入其中,点击登录即可 。
修改默认用户和密码
spring:
security:
user:
name: admin
password: 123456
小结
- 默认SpringSecurity是对所有的资源都进行拦截和保护,默认对/login开放
- 默认会创建一个账号名为:user,你可以在配置文件去覆盖默认用户和密码。
- 密码在:日志的中查看即可。默认密码是:UUID.random().toString();