目录
1、在pom.xml里面导入SpringSecurity的依赖
2、编写一个config,继承WebSecurityConfigureAdapter
不需要改动原来代码就可以添加很多拦截操作。AOP原理
在基本环境搭建好的前提下

创建SecurityConfig,继承WebSecurityConfigureAdapter,并添加注解@EnableWebSecurity


- // AOP 拦截器
- @EnableWebSecurity // 开启webSecurity模式 代表 SecurityConfig 被Spring托管了
- public class SecurityConfig extends WebSecurityConfigurerAdapter {
-
- // 授权
- @Override
- protected void configure(HttpSecurity http) throws Exception {
-
- // 首页所有人可以访问,功能页只有对应有权限的人才能访问
- // 请求授权的规则
- http.authorizeRequests()
- .antMatchers("/").permitAll()
- .antMatchers("/level1/**").hasRole("vip1")
- .antMatchers("/level2/**").hasRole("vip2")
- .antMatchers("/level3/**").hasRole("vip3");
-
- // 没有权限默认回到登录页面,需要开启登录的页面
- // /login
- http.formLogin();
- }
- }


这个是内存中的权限认证

- // 认证,springboot 2.1.x 可以直接使用
- // 密码编码: PasswordEncoder 不用密码编码登录的时候会报错
- // 在Spring Security 5.0+ 新增了很多加密方法
- @Override
- protected void configure(AuthenticationManagerBuilder auth) throws Exception {
-
- // 这些都是从数据库中读取
- auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
- .withUser("zhoujie").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1", "vip2", "vip3")
- .and()
- .withUser("root").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1", "vip2", "vip3")
- .and()
- .withUser("guest").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1");
- }
4.1、认证方法的源码

