Spring Security 是针对Spring项目的安全框架,也是Spring Boot底层安全模块默认的技术选型,他可以实现强大的Web安全控制,对于安全控制,我们仅需要引入 spring-boot-starter-security 模块,进行少量的配置,即可实现强大的安全管理!
记住几个类:
● WebSecurityConfigurerAdapter: 自定义Security策略
● AuthenticationManagerBuilder: 自定义认证策略
●@EnableWebSecurity:开启WebSecurity模式
Spring Security的两个主要目标是“认证”和“授权”(访问控制)。
“认证”(Authentication)
“授权”(Authorization)
这个概念是通用的,而不是只在Spring Security中存在。
1.添加spring-boot-starter-security启动器
- <dependency>
- <groupId>org.springframework.bootgroupId>
- <artifactId>spring-boot-starter-securityartifactId>
- dependency>
2.创建config文件夹,创建SecurityConfig类
- import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
- import org.springframework.security.config.annotation.web.builders.HttpSecurity;
- import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
- import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
- import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
-
- @EnableWebSecurity
- public class SecurityConfig extends WebSecurityConfigurerAdapter {
- //授权
- @Override
- protected void configure(HttpSecurity http) throws Exception{
- //首页所有人可以访问 功能页只有对应有权限的人才能访问
- http.authorizeRequests().antMatchers("/").permitAll()
- //vip1 才能访问1
- .antMatchers("/level1/**").hasRole("vip1")
- //vip2 才能访问2
- .antMatchers("/level2/**").hasRole("vip2")
- //vip3 才能访问3
- .antMatchers("/level3/**").hasRole("vip3");
- //没有权限默认会到登录页面,需要开启登录的页面
- http.formLogin();
- }
- //认证
- @Override
- protected void configure(AuthenticationManagerBuilder auth) throws Exception {
- //正常应该从数据库中读取
- auth.inMemoryAuthentication()
- .withUser("aaa").password(new BCryptPasswordEncoder().encode("123456")).roles("vip2","vip3")
- .and()
- .withUser("root").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1","vip2","vip3")
- .and()
- .withUser("guest").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1");
- }
- }
1.注销
- //注销回到首页
- http.logout().logoutSuccessUrl("/");
- //没有权限默认会登录页面
- http.formLogin().loginPage("/toLogin").usernameParameter("user").passwordParameter("pwd").loginProcessingUrl("/login");
2.权限控制
(1)添加依赖
- <dependency>
- <groupId>org.thymeleaf.extrasgroupId>
- <artifactId>thymeleaf-extras-springsecurity4artifactId>
- <version>3.0.4.RELEASEversion>
- dependency>
(2)修改前端页面添加
<div class="column" sec:authorize="hasRole('vip1')">
- //开启记住我功能
- http.rememberMe().rememberMeParameter("remember");