Spring Security相当于是一个springboot内部集成的一个安全框架
Spring Security 是针对Spring项目的安全框架,也是Spring Boot底层安全模块默认的技术选型,他可以实现强大的Web安全控制,对于安全控制,我们仅需要引入 spring-boot-starter-security 模块,进行少量的配置,即可实现强大的安全管理!记住几个类∶
WebSecurityConfigurerAdapter∶ 自定义Security策略AuthenticationManagerBuilder∶ 自定义认证策略
@EnableWebSecurity∶开启WebSecurity模式
授权:给进入的请求页面设置条件
认证:给要进入相关请求页面的用户设置权限,相当于认证一个用户(登记)
配置Spring Security
1.导入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
配置文件中关闭catch
spring.thymeleaf.cache=false
2.设置相关的配置类
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
//授权
protected void configure(HttpSecurity http) throws Exception {
//首页所有人可以访问,功能页只有对应的有权限的人才能访问
//请求授权的规则
http.authorizeRequests()
.antMatchers("/").permitAll()
.antMatchers("/level1/**").hasAnyRole("vip1")
.antMatchers("/level2/**").hasAnyRole("vip2")
.antMatchers("/level3/**").hasAnyRole("vip3");
//没有权限默认到登录界面,需要开启登录的页面、
//这个登录界面是自带的
http.formLogin()
}
//密码编码
//在spring security 5 新增了很多加密方式 没有加密的话不能用
//密码编码 BCryptPasswordEncoder()
@Override
//认证
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
.withUser("zhou").password(new BCryptPasswordEncoder().encode("1234")).roles("vip2","vip3")
.and()
.withUser("root").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1","vip2","vip3")
.and()
.withUser("guest").password(new BCryptPasswordEncoder().encode("1")).roles("vip1");
}
}
3.注销
//注销 注销成功返回首页
http.logout().logoutSuccessUrl("/");
4.记住我
前端代码
<div class="field">
<input type="checkbox" name="remember">记住我
</div>
配置类代码
http.rememberMe().rememberMeParameter("remember");
5自定义登录页
登录页默认的是自带的
http.formLogin() .loginProcessingUrl("/login") //当发现/login请求时认为是登录 执行登录
.loginPage("/login.html");