SpringSecurity安全框架


SpringSecurity

AOP  :截面 —— 配置类

SpringSecurity是针对Spring项目的安全框架,spring Boot底层安全模块默认的技术选型,只需要引入spring-boot-starter-security,进行少量配置,即可实现强大的安全管理

主要的几个类

WebSecurityConfigurerAdapter  :自定义Security策略   运用了: 适配器模式  

AuthenticationManagerBuilder: 自定义认证策略       运用了: 建造者模式  

@EnableWebSecurity: 开启webSecurity模式

SpringSecurity主要目标  “认证”和“授权”(访问控制)

“认证”(Authentication)

“授权”(Authorization)  

官网:https://spring.io/projects/spring-security/

项目版本,对应的帮助文档https://docs.spring.io/spring-security/site/docs/5.2.0.RELEASE/reference/htmlsingle/


    org.springframework.boot
    spring-boot-starter-security

配置类配置

@EnableWebSecurity
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {
    //链式编程 //授权
    @Override
    protected void configure(HttpSecurity http) throws Exception {
//首页所有人都可以访问,功能页面对应有权限的人才能访问
http.authorizeRequests().antMatchers("/").permitAll()  //这个代表所有人都能访问
.antMatchers("/leve1/**").hasRole("vip1") //拥有权限vip1可以访问leve1下面的所有页面

.antMatchers("/leve2/**").hasRole("vip2")//拥有权限vip2可以访问leve2下面的所有页面
.antMatchers("/leve3/**").hasRole("vip3") ;//拥有权限vip3可以访问leve3下面的所有页面
//没有权限默认会到登录页面
http.formLogin(); }
    //认证
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {      
    }

 

 

但是 spring  Secutiry 5.0+ 新增了很多的加密方法,不加密报错

@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
  auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())//内存里认证
  .withUser("zhangsan").password(new BCryptPasswordEncoder().encode("123456")).roles("vip2","vip3")
 .and()
 .withUser("root").password(newBCryptPasswordEncoder().encode("root").roles("vip1","vip2","vip3");
}

 

@Autowiredprivate DataSource dataSource;

@Autowiredpublic void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {

    // ensure the passwords are encoded properly

    UserBuilder users = User.withDefaultPasswordEncoder();

    auth

        .jdbcAuthentication()

            .dataSource(dataSource)

            .withDefaultSchema()

            .withUser(users.username("user").password("password").roles("USER"))

            .withUser(users.username("admin").password("password").roles("USER","ADMIN"));

 

 不解可以评论留言或者加微信(yswsxf1314)讨论

相关