SpringBoot 2.x + SpringSecurity 5.0.6 結(jié)合數(shù)據(jù)庫安全認(rèn)證

相關(guān)資料以及注意事項(xiàng):

一.Maven配置

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <!--thymeleaf調(diào)用spring security工具-->
        <dependency>
            <groupId>org.thymeleaf.extras</groupId>
            <artifactId>thymeleaf-extras-springsecurity4</artifactId>
        </dependency>
        <!--druid數(shù)據(jù)連接池-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.1.10</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>


        <!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
        <!--在idea中需要安裝lombok插件-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.0</version>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <optional>true</optional>
        </dependency>
    </dependencies>

二.文件結(jié)構(gòu)

└─com
    └─example
        └─securityjpa
            │  SecurityJpaApplication.java
            │  
            ├─config
            │      DruidConfig.java Druid配置文件
            │      SecurityConfig.java SpringSecurity配置文件
            │      
            ├─controller
            │      CommonController.java 頁面映射
            │      
            ├─entity
            │      RoleEntity.java 角色類型
            │      UserEntity.java 用戶類型
            │      
            ├─handler
            │      CustomAccessDeniedHandler.java 自定義授權(quán)失敗
            │      myPassWordEncoder.java 自定義密碼加密規(guī)則
            │      
            ├─jpa
            │      UserEntityJpa.java JPA連接類
            │      
            └─service
                    UserService.java 自定義用戶用戶認(rèn)證規(guī)則

說實(shí)話,大概踩了一個(gè)禮拜的坑,今天終于把坑全部填平了,SpringSecurity5.0的改動(dòng)內(nèi)容實(shí)在是多,接下來把有關(guān)于SpringSecurity的配置慢慢講來。此處省略了一些非核心代碼。

a.UserService+UserEntity認(rèn)證規(guī)則以及用戶對(duì)象類

/**
 * 自定義身份認(rèn)證
 * 需要實(shí)現(xiàn)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中,用戶表對(duì)象類需要實(shí)現(xiàn)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<RoleEntity> roles;


    //設(shè)置用戶身份權(quán)限
    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        List<GrantedAuthority> authorities = new ArrayList<>();
        List<RoleEntity> roles = getRoles();
        for (RoleEntity role : roles) {
            authorities.add(new SimpleGrantedAuthority(role.getName()));
        }
        return authorities;
    }
    //設(shè)置用戶密碼
    @Override
    public String getPassword() {
        return password;
    }
    //設(shè)置用戶名
    @Override
    public String getUsername() {
        return username;
    }
    //設(shè)置賬戶沒有過期
    @Override
    public boolean isAccountNonExpired() {
        return true;
    }
   //設(shè)置賬戶沒有被鎖
    @Override
    public boolean isAccountNonLocked() {
        return true;
    }
   //設(shè)置認(rèn)證沒有過期
    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }
   //設(shè)置用戶可以用
    @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會(huì)默認(rèn)在身份前加上前綴,這里設(shè)置去除
    @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();
    }

    /**
     * 注入自定義認(rèn)證類
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(getServiceDetail());
    }

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

        /*匹配所有路徑的*/
        http
                /*關(guān)閉跨站支持,不關(guān)閉的話,無法登陸Druid監(jiān)控頁面*/
                .csrf()
                .disable()
                .authorizeRequests()
                .antMatchers("/").permitAll()
            ...
            ...
            ...
              
    }
}

c.JPA配置類

/**

- 用戶信息JPA,JPA中只要按照命名規(guī)則,JPA會(huì)自動(dòng)配置查找方法,無需實(shí)現(xiàn)
- @author BaoZhou
- @date 2018/7/4
  */
  public interface UserEntityJpa extends JpaRepository<UserEntity,Long> {
  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的配置

收工!

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容