SpringBoot 2.x + SpringSecurity 5.0.6 结合数据库安全认证

相关资料以及注意事项:

  • SpringSecurity参考手册官方文档
  • 本文工程GitHub
  • SpringSecurity内存方式管理版本
  • 本文环境:SpringBoot 2.x + SpringSecurity 5.0.6 + SpringJPA + Druid + mySQL + Thymeleaf + Lomok
  • 注意:由于引入Lomok,所以需要安装Lomok插件,否则程序无法运行。

一.Maven配置

    
        
            org.springframework.boot
            spring-boot-starter-data-jpa
        
        
            org.springframework.boot
            spring-boot-starter-jdbc
        
        
            org.springframework.boot
            spring-boot-starter-security
        
        
            org.springframework.boot
            spring-boot-starter-web
        

        
            org.springframework.boot
            spring-boot-starter-thymeleaf
        
        
        
            org.thymeleaf.extras
            thymeleaf-extras-springsecurity4
        
        
        
            com.alibaba
            druid-spring-boot-starter
            1.1.10
        

        
            mysql
            mysql-connector-java
            runtime
        


        
        
        
            org.projectlombok
            lombok
            1.18.0
            provided
        

        
            org.springframework.boot
            spring-boot-starter-test
            test
        

        
            org.springframework.security
            spring-security-test
            test
        

        
            org.springframework.boot
            spring-boot-devtools
            true
        
    

二.文件结构

└─com
    └─example
        └─securityjpa
            │  SecurityJpaApplication.java
            │  
            ├─config
            │      DruidConfig.java Druid配置文件
            │      SecurityConfig.java SpringSecurity配置文件
            │      
            ├─controller
            │      CommonController.java 页面映射
            │      
            ├─entity
            │      RoleEntity.java 角色类型
            │      UserEntity.java 用户类型
            │      
            ├─handler
            │      CustomAccessDeniedHandler.java 自定义授权失败
            │      myPassWordEncoder.java 自定义密码加密规则
            │      
            ├─jpa
            │      UserEntityJpa.java JPA连接类
            │      
            └─service
                    UserService.java 自定义用户用户认证规则

说实话,大概踩了一个礼拜的坑,今天终于把坑全部填平了,SpringSecurity5.0的改动内容实在是多,接下来把有关于SpringSecurity的配置慢慢讲来。此处省略了一些非核心代码。

a.UserService+UserEntity认证规则以及用户对象类

/**
 * 自定义身份认证
 * 需要实现UserDetailsService接口
 * @author BaoZhou
 * @date 2018/7/4
 */
public class UserService implements UserDetailsService {
    @Autowired
    UserEntityJpa userEntityJpa;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        UserEntity userEntity = userEntityJpa.findByUsername(username);
        if (userEntity == null) {
            throw new UsernameNotFoundException("未找到用户名");
        }
        return userEntity;
    }
}
/**
 * 用户类
 * 在SpringSecurity中,用户表对象类需要实现UserDetails接口
 *
 * @author BaoZhou
 * @date 2018/7/4
 */
@Entity
@Table(name = "users")
@Getter
@Setter
public class UserEntity implements Serializable, UserDetails {

    @Id
    @Column(name = "u_id")
    private Long id;
    @Column(name = "u_username")
    private String username;
    @Column(name = "u_password")
    private String password;
    @ManyToMany(fetch = FetchType.EAGER)
    @JoinTable(
            name = "user_roles",
            joinColumns = {
                    @JoinColumn(name = "ur_user_id")
            },
            inverseJoinColumns = {
                    @JoinColumn(name = "ur_role_id")
            }
    )
    private List roles;


    //设置用户身份权限
    @Override
    public Collection getAuthorities() {
        List authorities = new ArrayList<>();
        List roles = getRoles();
        for (RoleEntity role : roles) {
            authorities.add(new SimpleGrantedAuthority(role.getName()));
        }
        return authorities;
    }
    //设置用户密码
    @Override
    public String getPassword() {
        return password;
    }
    //设置用户名
    @Override
    public String getUsername() {
        return username;
    }
    //设置账户没有过期
    @Override
    public boolean isAccountNonExpired() {
        return true;
    }
   //设置账户没有被锁
    @Override
    public boolean isAccountNonLocked() {
        return true;
    }
   //设置认证没有过期
    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }
   //设置用户可以用
    @Override
    public boolean isEnabled() {
        return true;
    }

b.SecurityConfig配置类

/**
 * @author: BaoZhou
 * @date : 2018/7/4 17:15
 */
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Bean
    UserDetailsService getServiceDetail() {
        return new UserService();
    }

    //SpringSecurity会默认在身份前加上前缀,这里设置去除
    @Override
    public void configure(WebSecurity web) throws Exception {
        web.expressionHandler(new DefaultWebSecurityExpressionHandler() {
            @Override
            protected SecurityExpressionOperations createSecurityExpressionRoot(Authentication authentication, FilterInvocation fi) {
                WebSecurityExpressionRoot root = (WebSecurityExpressionRoot) super.createSecurityExpressionRoot(authentication, fi);
                //remove the prefix ROLE_
                root.setDefaultRolePrefix("");
                return root;
            }
        });
    }
    //SpringSecurity5.0.6必须使用加密算法,此处注入加密方法
    @Bean
    public BCryptPasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    /**
     * 注入自定义认证类
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(getServiceDetail());
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        /*匹配所有路径的*/
        http
                /*关闭跨站支持,不关闭的话,无法登陆Druid监控页面*/
                .csrf()
                .disable()
                .authorizeRequests()
                .antMatchers("/").permitAll()
            ...
            ...
            ...
              
    }
}

c.JPA配置类

/**

- 用户信息JPA,JPA中只要按照命名规则,JPA会自动配置查找方法,无需实现
- @author BaoZhou
- @date 2018/7/4
  */
  public interface UserEntityJpa extends JpaRepository {
  public UserEntity findByUsername (String username);

}

三.配置文件

spring:
  datasource:
    username: root
    password: 123456
    url: jdbc:mysql://192.168.15.128:3306/jdbc
    driver-class-name: com.mysql.jdbc.Driver
    type: com.alibaba.druid.pool.DruidDataSource
    initialSize: 5
    minIdle: 5
    maxActive: 20
    maxWait: 60000
    timeBetweenEvictionRunsMillis: 60000
    minEvictableIdleTimeMillis: 300000
    validationQuery: SELECT 1 FROM DUAL
    testWhileIdle: true
    testOnBorrow: false
    testOnReturn: false
    poolPreparedStatements: true
    filters: {stat,wall,log4j}
    maxPoolPreparedStatementPerConnectionSize: 20
    useGlobalDataSourceStat: true
    connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
  jpa:
      show-sql: true
      hibernate:
        ddl-auto: update
server:
  port: 8005

配置文件中主要是Druid与JPA的配置

收工!

你可能感兴趣的:(SpringBoot 2.x + SpringSecurity 5.0.6 结合数据库安全认证)