SpringSecurity环境搭建

SpringSecurity环境搭建_第1张图片

AOP思想:面向切面编程 

SpringSecurity环境搭建_第2张图片

 

导入依赖 



    4.0.0
    
        org.springframework.boot
        spring-boot-starter-parent
        2.7.14
         
    
    com.qf
    springboot-06-security
    0.0.1-SNAPSHOT
    springboot-06-security
    springboot-06-security
    
        1.8
    
    
        
            org.springframework.boot
            spring-boot-starter-web
        

        
            org.springframework.boot
            spring-boot-starter-test
            test
        
 
        
            org.thymeleaf
            thymeleaf-spring5
        
        
            org.thymeleaf.extras
            thymeleaf-extras-java8time
        
    

    
        
            
                org.springframework.boot
                spring-boot-maven-plugin
            
        
    


SpringSecurity环境搭建_第3张图片

 导入素材

配置类

package com.qf.config;

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()
                .antMatchers("/level1/**").hasRole("vip1")
                .antMatchers("/level1/**").hasRole("vip2")
                .antMatchers("/level1/**").hasRole("vip3");

        //没有权限默认会到登录页面,需要开启登录的页面

            http.formLogin();

    }

    //认证,springboot2.1可以直接使用~
    //密码编码:PasswordEncoder
    //在spring Secutiry 5.0+ 新增了很多的加密方法~

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {

        //这些数据正常应该从数据中读
        auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
                .withUser("kuangshen").password(new BCryptPasswordEncoder().encode("123456")).roles("vip2","vip3")
                .and()
                .withUser("root").password(new BCryptPasswordEncoder().encode("123456")).roles("vip2","vip3","vip1")
                .and()
                .withUser("guest").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1");




    }
}

你可能感兴趣的:(SpringBoot,spring,boot)