SpringSecurity简介
SpringSecurity是SpringBoot中集成的权限框架,可定制身份验证和权限控制。侧重于为java应用程序提供身份验证和授权。解决之前关于权限的代码十分繁琐,冗余的问题。SpringSecurity主要有两个目标:认证(Authentication)和授权(Authorization)
一、搭建SpringSecurity环境
1、引入spring-boot-starter-security模板,在idea工具中,可以直接在创建SpringBoot项目时勾选。
2、也可以在maven中手动加入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
3、导入依赖之后,在项目目录下创建SpringSecurity的配置类。
需要继承WebSecurityConfigurerAdapter类并且重写它的一些方法。
二、认证和授权
1、添加授权
@Override
protected void configure(HttpSecurity http) throws Exception {
//首页所有人可以访问,功能也需要权限
//链式编程
//授权
http.authorizeRequests()
.antMatchers("/").permitAll()
.antMatchers("/level1/**").hasRole("vip1")
.antMatchers("/level2/**").hasRole("vip2")
.antMatchers("/level3/**").hasRole("vip3");
//没有权限默认回到登录页面
//自定义登录页,设置表单提交的name属性值,设置请求过滤路径
http.formLogin().loginPage("/toLogin").usernameParameter("user").passwordParameter("pwd").loginProcessingUrl("/login");
//关闭防止网站攻击,springboot默认开启,注销失败的原因可能是开启了防止网站攻击
http.csrf().disable();
//注销
http.logout();
//开启记住我功能,cookie,默认保存两周。自定义记住我功能,需要传递参数
http.rememberMe(