1. SpringSecurity简介
依赖于Maven环境
提供“认证”和“授权”保护
2. 开发环境
2.1 新建Springboot项目
TODO
2.3 作成Controller访问类
TODO
3. 修改配置
3.1 POM引入SpringSecurity依赖
可以通过这个网址查找Springboot的依赖https://docs.spring.io/spring-boot/docs/2.0.3.RELEASE/reference/htmlsingle/#using-boot-starter
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
注释:引入后注意刷新maven
3.2 新建config
1.在config包下,新建xxxConfig类
2.继承 WebSecurityConfigurerAdapter 类
3.追加类注解 @EnableWebSecurity
4.重写configure(HttpScurity http)方法(授权)
http.authorizeRequests() //认证请求
.antMatchers("/").permitAll() // 请求路径,permitAll所有人可以
.antMatchers("/v1").hasRole("vip1") // vip1权限可以访问 v1请求
http.formLogin(); // 没有权限跳转login请求 (默认:Login,可指定url)
http.logout(); // 注销
http.logout().deleteCookies("remove").invalidateHttpSession(false); //注销,清除cookie和session
http.logout().logoutUrl("/index"); // 注销成功跳转请求
http.csrf().disable(); // 防止网站攻击(关闭跨站请求伪造)
5.重写configure(AuthenticationManagerBuilder auth)方法(认证)
auth.jdbcAuthentication // JDBC数据库认证(两种认证二选一)
auth.inMemoryAuthentication // 内存认证(两种认证二选一)
.withUser("user1").password("123456").roles("vip1")
.and()
.withUser("user2").password("123456").roles("vip2")
注释:SpringSecurity2.1.0及以上版本密码需要加密
auth.inMemoryAuthentication.passwordEncoder(new BCryptPasswordEncoder())
.withUser("user1").password(new BCryptPasswordEncoder("123456")).roles("vip1")