Spring Security5.5.1

1. spring boot 2.3中如何禁用spring security

//环境 spring boot 2.3, 依赖spring security版本是5.5.1,增加配置文件

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //super.configure(http);所有的请求将全部通过
        http.authorizeRequests(au -> au.anyRequest().permitAll());
    }
}

 2.基于内存的认证登陆

@Configuration
@EnableWebSecurity//两个作用,1: 加载了WebSecurityConfiguration配置类, 配置安全认证策略。2: 加载了AuthenticationConfiguration, 配置了认证信息
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Bean
    PasswordEncoder passwordEncoder(){
        //如果加密 return new BCryptPasswordEncoder();
        return NoOpPasswordEncoder.getInstance();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //super.configure(auth);
        //如果加密  PasswordEncoder pa = passwordEncoder();
       
        auth.inMemoryAuthentication()
                .withUser("one").password("one").roles("admin").and()
                .withUser("two").password("two").roles("operator");
                //如果加密 .withUser("two").password(pa.encode("two")).roles("operator");

    }
}

 3.基于角色的访问

//1.配置类里定义用户与角色
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
                .withUser("one").password("one").roles("admin").and()
                .withUser("two").password("two").roles("normal");
    }

//2.在此类上加入注解
@EnableGlobalMethodSecurity(prePostEnabled = true) //启用方法级别认证
public class SecurityConfig extends WebSecurityConfigurerAdapter

//3.控制器里设置访问角色
    @GetMapping("/helloUser")
    @PreAuthorize(value = "hasAnyRole('admin','normal')")
    public String HelloCommonUser(){
        return "这是普通用户和管理员都可以访问";
    }
    @GetMapping("/helloAdmin")
    @PreAuthorize(value = "hasAnyRole('admin')")
    public String HelloAdmin(){
        return "这是管理员可以访问";
    }

 4.Hibernate引入数据库

//1.maven 中引入
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.29</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
            <version>2.5.4</version>
        </dependency>
    再定义配置文件 
    spring.datasource.url=jdbc:mysql://localhost:3306/bing
    spring.datasource.username=root
    spring.datasource.password=
    spring.datasource.driver-class-name=com.mysql.jdbc.Driver

    spring.jpa.generate-ddl=true
    spring.jpa.show-sql=true
    spring.jpa.database=mysql

//2.定义实体类entity->userinfo.java
@Data
@Entity
public class UserInfo { //类名自动存表名,大写会转成下划线
    @Id //指定当前属性为主键
    @GeneratedValue(strategy = GenerationType.IDENTITY) //自动递增
    private Long id;

    private String username;

    private String password;

    private String role;
}

//3.定义dao, dao->userInfoDao.java
public interface UserInfoDao extends JpaRepository<UserInfo,Long> { //传入实体类,与主键类型

    UserInfo findByUsername(String username);
    
}

4.创建service,与serviceImpl实现类
5.往数据库自定义填充一些数据进去 init/jdbcInit.java
@Component
public class JdbcInit {
    @Autowired
    private UserInfoDao dao;

    @PostConstruct //在服务器加载Servlet的时候运行,并且只会被服务器执行一次,只能修饰非静态的void
    public void init(){
        PasswordEncoder pa = new BCryptPasswordEncoder();
        UserInfo u = new UserInfo();
        u.setUsername("abing");
        u.setPassword(pa.encode("12345"));
        u.setRole("normal");
        dao.save(u);
        UserInfo u2 = new UserInfo();
        u2.setUsername("admin");
        u2.setPassword(pa.encode("admin"));
        u2.setRole("admin");
        dao.save(u2);

    }
}

 5.从数据库中获取用户信息和权限的认证

//1.定义provider/myUserdetailService.java 查询用户信息并实现security的userdetail.用户信息
@Component
public class MyUserDetailService implements UserDetailsService {
    @Autowired
    private UserInfoDao dao;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        User user = null;
        if(s != null){
            UserInfo userInfo = dao.findByUsername(s);
            List<GrantedAuthority> aut = new ArrayList<>();
            //这里一定要加ROLE_,不然用不了
            GrantedAuthority grantedAuthority = new SimpleGrantedAuthority("ROLE_"+userInfo.getRole());
            aut.add(grantedAuthority);
            if(userInfo != null){
                user = new User(userInfo.getUsername(),userInfo.getPassword(),aut);
            }
        }

        return user;
    }
}
//2.上面返回了用户对象后,再配置到SecurityConfig extends WebSecurityConfigurerAdapter的config里 public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private MyUserDetailService myUserDetailService; @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(myUserDetailService).passwordEncoder(new BCryptPasswordEncoder()); } //然后再进行登陆测试正常

原文地址:https://www.cnblogs.com/bing2017/p/15292411.html