在正常的开发中,想必大家都知道有用户、管理员和vip的专属功能,呢么是怎么分层确认谁的权限呢? 这里为大家介绍一下用SpringSecurity解决权限问题。
springSecurity官网介绍(汉化后)
Spring Security是一个功能强大且高度可定制的身份验证和访问控制框架。它实际上是保护基于spring的应用程序的标准。
Spring Security是一个框架,侧重于为Java应用程序提供身份验证和授权。与所有Spring项目一样,Spring安全性的真正强大之处在于它可以轻松地扩展以满足定制需求。
官网地址:https://spring.io/projects/spring-security
认证:通过用户名和密码来验证身份。
授权:能够使用和访问资源的多少。
需求依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
几个关键类
@WebSecurityConfigurerAdapter:自定义Security策略
@AuthenticationManagerBuilder:自定义认证策略
@EnableWebSecurity:开启WebSecurity模式
授权
在进行权限管理时,需要继承WebSecurityConfigurerAdapter类
这里对configure方法进行了重载,在这里可以基于不同的请求方式来对用户进行授权。
protected void configure(HttpSecurity http) throws Exception {
// 首页全部能访问 功能对应有权限的访问
http.authorizeHttpRequests().antMatchers("/").permitAll() //全员访问
.antMatchers("/level1/**").hasRole("vip1") //对应相关人员
.antMatchers("/level2/**").hasRole("vip2")
.antMatchers("/level3/**").hasRole("vip3");
// 没有权限 默认返回到登录页
http.formLogin();
}
对用户授权后,发现除了首页其他所有页面都访问不了了, 是因为我们还没给用户进行认证。
认证
定义认证规则,去重写configure方法
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// 正常应该从数据库中读取 目前采取从内存中读取
auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
.withUser("tdj").password("123456").roles("vip1","vip2").and()
.withUser("root").password(new BCryptPasswordEncoder().encode("root")).roles("vip1","vip2","vip3");
}
这里的数据是直接使用的内存中的,并没有去接数据库。且在SpringSecurity中必须要对密码加密否则会报错
加密方式:
去调用passwordEncoder(new BCryptPasswordEncoder())来修改密码编码。
修改完密码加密后,就实现了给用户分配权限,且只能访问自己权限内的页面。