一、是什么(what)
Spring Security是一个框架,提供身份验证、授权和针对常见攻击的保护。由于对保护命令式和反应式应用程序的一流支持,它是保护基于Spring的应用程序的事实标准。
二、为什么用(why)
例如:我们用的操作系统都有root 和普通用户 所以在我们创建一些web应用时应该给不同用户添加一些权限来限定不同用户的操作为了简化实现权限认证操作功能spingsecurity就此诞生
三、怎么用(how)
1.导入pom依赖(springboot项目)
<!-- spring security -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
其他项目请移步官网:sping-security
2. 创建securityConfig配置类
package com.example.config;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
//链式编程
@EnableWebSecurity
public class securityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
//请求授权的规则
http.authorizeRequests()
.antMatchers("/").permitAll()
.antMatchers("/index1.html").hasRole("vip1")
.antMatchers("/index2.html").hasRole("vip2")
.antMatchers("/index3.html").hasRole("vip3");
//启动规则
http.formLogin();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
.withUser("wyh").password(new BCryptPasswordEncoder().encode("123456")).roles("vip2","vip3")
.and()
.withUser("root").password(new BCryptPasswordEncoder().encode("123456")).roles("vip2","vip1","vip3")
.and()
.withUser("guest").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1")
;
}
}