Spring Security 是 Spring 家族中的一个重要的安全管理框架(底层是拦截器和过滤器),一般多用于JavaWEB项目,对整个项目的授权、认证以及攻击防护(伪造身份)进行监管控制,例如,在一个学生上课考勤管理系统的web项目中,登录角色一般情况下分为两种,一个是老师(管理员),一个是学生(普通用户),系统有些模块页面学生和老师都能访问得到,比如登录页,首页等等,而其他功能页,诸如添加学生、删除学生、查询某个学生、显示所有或某个学生的考勤情况等等,这些功能页,应该只有老师才有权限访问和操作,而用户在登录之初,系统就会根据登录用户的登录信息对登录用户进行角色判断,判断你是管理员还是普通用户,然后,根据业务判断程序,匹配相应的权限给相应的角色,而springSecurity就是为了解决这个问题而生的,但它并不是唯一的。
1、快速入门
新建一个spring boot项目,在pom.xml里面导入springSecurity的依赖
<!--security-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
2、初次体验
我们创建一个 HelloController:
@RestController
public class HelloController {
@GetMapping("/hello")
public String hello() {
return "hello";
}
}
访问 /hello ,会出现以下springSecurity自带的登录页,需要登录之后才能访问下一个页面(自定义的,需要编写请求跳转接口和对应的访问页)。
3、案例演示
静态资源
首页
点击 level1-1进去后的样式,level1-3类似。
以上level~系列静态资源,都包含在index首页中。
登录页
4、定义一个SecurityConfig类来对该项目进行授权认证和防攻击操作
4.1、授权:
package com.kuang.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;
//AOP : 拦截器(横切)
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
//链式编程(追加)
//授权
@Override
protected void configure(HttpSecurity http) throws Exception {
//首页所有人都可以访问,功能页只有对应权限的人才可以访问
//请求授权的规则
//antMatchers 资源匹配
//hasRole 角色
http.authorizeRequests().antMatchers("/").permitAll()
.antMatchers("/level1/**").hasRole("vip1")
.antMatchers("/level2/**").hasRole("vip2")
.antMatchers("/level3/**").hasRole("vip3");
//没有授权默认会回到登录页
//.loginPage("/toLogin") : 定制登录页,使用自己的登录页,不用Security自带的登录页 ---> http.formLogin()
http.formLogin().loginPage("/toLogin").loginProcessingUrl("/login"); // /toLogin 映射到 /login
//防止网站被攻击:get post
http.csrf().