【安全框架】Spring Security安全框架

时间:2025-03-10 21:28:52

Spring Security 是针对Spring项目的安全框架,仅需要引入 spring-boot-starter-sercurity 模块。

  • WebSecurityConfigurerAdapter:自定义Security策略。
  • AuthenticationManagerBuilder:自定义认证策略。
  • @EnableWevSecurity:开启WebSecurity模式。

Spring Security的两个主要目标是“认证”和“授权”(访问控制)。
”认证“(Authentication)、”授权“(Authorization)

1、引入依赖
<!-- security-thymeleaf整合包 -->
<dependency>
    <groupId></groupId>
    <artifactId>thymeleaf-extras-springsecurity4</artifactId>
    <version>3.0.</version>
</dependency>

<!-- security -->
<dependency>
	<groupId></groupId>
	<artifactId>spring-boot-starter-security</artifactId>
</dependency>

<!-- thymeleaf模板 -->
<dependency>
    <groupId></groupId>
    <artifactId>thymeleaf-spring5</artifactId>
</dependency>
<dependency>
    <groupId></groupId>
    <artifactId>thymeleaf-extras-java8time</artifactId>
</dependency>
2、创建 SecurityConfig
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

	// 授权
	@Override
	protected void configure(HttpSecurity http) throws Exception {
		// 首页所有人可以访问,功能页只有对应有权限的人才能访问
		// 请求授权的规则
		()
			.antMatchers("/").permitAll
			.antMatchers("/level1/**").hasRole("vip1")
			.antMatchers("/level2/**").hasRole("vip2")
			.antMatchers("/level3/**").hasRole("vip3");

		// 没有权限默认会到登录页面,需要开启登录的页面
		()
			.loginPage("/toLogin");

		// 注销,开启注销功能,跳到指定首页界面
		().logoutSuccessUrl("/index");

		// 开启记住我功能, 默认保存两周,自定义接收前端的参数
		().rememberMeParameter("remember");
	}

	// 认证,SpringBoot 2.可以直接使用
	// 密码编码:PasswordEncoder
	// 在 Spring Secutiry 5.0+ 新增了很多的加密方法~
	@Override
	protected void configure(AuthenticationManagerBuilder auth) throws Exception {
		// 数据正常应该从数据库中读取
		// new BcryptPasswordEncoder()  : 密码加密编码
		().passwordEncoder(new BcryptPasswordEncoder())
			.withUser("username1").passowrd(new BcryptPasswordEncoder().encode("123456")).roles("vip1","vip3")
			.and()
			.withUser("username2").passowrd(new BcryptPasswordEncoder().encode("123456")).roles("vip1","vip2","vip3");
	}

}