Spring Security 基于 Spring 框架,提供了一套 Web 应用安全性的完整解决方案。一般来说,Web 应用的安全性包括用户认证(Authentication)和用户授权(Authorization)两个部分。
- 用户认证指的是验证某个用户是否为系统中的合法主体,也就是说用户能否访问该系统。用户认证一般要求用户提供用户名和密码。系统通过校验用户名和密码来完成认证过程
- 用户授权指的是验证某个用户是否有权限执行某个操作
注意:每一个用户可以对应多个角色,一个角色可以对应多个可以访问的资源权限
步骤(2步)
- 导入依赖
- 编写配置类
导入依赖:新版的springboot 使用security需要引入3个依赖
org.springframework.security
spring-security-core
org.springframework.security
spring-security-web
org.springframework.security
spring-security-config
org.thymeleaf.extras
thymeleaf-extras-springsecurity5
编写SecurityConfig :需要继承WebSecurityConfigurerAdapter
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
//授权 什么角色可以访问什么资源
@Override
protected void configure(HttpSecurity http) throws Exception {
//什么角色可以访问什么资源 antPatterns:访问路径
http.authorizeRequests().antMatchers("/").permitAll()
.antMatchers("/level1/**").hasRole("role1")
.antMatchers("/level2/**").hasRole("role2")
.antMatchers("/level3/**").hasRole("role3");
//开启自动配置的登录功能
http.formLogin()
.loginPage("/login.html")//设置登录页(自定义登录页面)
.usernameParameter("username")//如果表单的username的name不是username需要单独配置
.passwordParameter("password")//如果表单的password的name不是password需要单独配置
.loginProcessingUrl("/login");//登录表单提交请求路径
// post请求发送
http.csrf().disable();
//注销功能 注销之后 返回至首页
http.logout().logoutSuccessUrl("/");
//请记住我 会将信息存入cookie中 默认保存14天
http.rememberMe().rememberMeParameter("remember");
}
// 认证
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// 密码需要进行加密 不能使用明码
auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
.withUser("tom").password(new BCryptPasswordEncoder().encode("123456")).roles("role1").and()
.withUser("tony").password(new BCryptPasswordEncoder().encode("123456")).roles("role1","role2").and()
.withUser("root").password(new BCryptPasswordEncoder().encode("123456")).roles("role1","role2","role3");
}
}
@EnableWebSecurity:自动装配WebSecurity
如果写http.formLogin();表示使用框架自带的登录页面
该示例没有使用数据库,所以使用了内存来存放认证信息
这个配置类是使用链式编程的思想
实现注销
- 编写语句:http.logout().logoutSuccessUrl("/");
- url:/logout 这个路径是springsecurity框架为我们提供的
实现自动登录
- 编写语句:http.rememberMe();
- 如果是自定义登录页面: http.rememberMe().rememberMeParameter("remember");(登录表单 多选框的name是remember)
thymeleaf与springboot进行整合
需要导入命名空间
xmlns:sec="http://www.thymeleaf.org/extras/spring-security"
关键字介绍
sec:authorize 表示判断用户的普通权限
具体的value:
- isAuthenicated() 用户成功登录 则显示
- hasRole("A")用户具有A权限,则显示
sec:authentication 表示当前用户对象
具体的value:
- name:用户名
- authentication:权限名称
示例代码
首页
.div_1{
float: left;
}
登录
用户: 权限:
注销
- 1-1
- 1-2
- 1-3
- 2-1
- 2-2
- 2-3
- 3-1
- 3-2
- 3-3
运行结果
在没有登录时,是没有任何权限的,所以只显示登录链接
登录成功,页面会显示用户的相关信息
注销后回到首页
换一个账号登录 ,以验证 账号之间的区别



