SpringBoot 与 SpringSecurity
一、环境搭建
(1)IDEA创建SpringBoot工程
(2)导入依赖
(3)如果是thymeleaf项目 需导入thymeleaf整合security的依赖
(4)编写配置类(采用AOP横切入程序中)
(1)SecurityConfig类继承 WebSecurityConfigurerAdapter类,WebSecurityConfigurerAdapter 类是个适配器, 在配置的时候,需要我们自己写个配置类去继承他,然后编写自己所特殊需要的配置。
(2)采用注解@EnableWebSecurity(该注解的作用,如下图)
作用:(1)激活了WebSecurityConfiguration配置类,在这个配置类中, 注入了一个非常重要的bean, bean的name为: springSecurityFilterChain,这是Spring Secuity的核心过滤器, 这是请求的认证入口。
(2)激活了AuthenticationConfiguration配置类, 这个类是来配置认证相关的核心类, 这个类的主要作用是,向spring容器中注入AuthenticationManagerBuilder, AuthenticationManagerBuilder其实是使用了建造者模式, 他能建造AuthenticationManager, 这个类前面提过,是身份认证的入口。
(5)配置类采用(链式编程)
(1)在该类中重写2个方法。如图,第一个方法是授权,第二个方法是认证
(2)在第一个方法中实现了首页可以所有人可以访问,功能页只有相应有权限的人才能访问(类似于腾讯视频普通用户、VIP、超前点播的层次)
http.authorizeRequests().antMatchers(“/”).permitAll()
.antMatchers(“/level1/**”).hasRole(“VIP1”)
.antMatchers(“/level2/**”).hasRole(“VIP2”)
.antMatchers(“/level3/**”).hasRole(“VIP3”);
(3)如果没有权限返回到登陆页面
http.formLogin();
(4)关闭其他网站通过get post put方式攻击本网站 关闭csrf(csrf又称跨域请求伪造,攻击方通过伪造用户请求访问受信任站点。)
http.csrf().disable();
(5)开启注销功能
http.logout().logoutSuccessUrl(“/”);
(3)第二个方法里认证需采用 new BCryptPasswordEncoder();对密码进行加密
auth.inMemoryAuthentication.passwordEncoder(new BCryptPasswordEncoder)
(正常来讲,数据都从数据库获取)
.withUser("downson").password(new BCryptPasswordEncoder().encode("dw")).roles("vip2","vip3")
.and()
.withUser("root").password(new BCryptPasswordEncoder().encode("dw")).roles("vip1","vip2","vip3")
.and()
.withUser("guest").password(new BCryptPasswordEncoder().encode("dw")).roles("vip1");