Spring Security 整合 thymeleaf 實現動態權限 (2)項目基本配置

項目基本配置

建立一個基本的springboot項目。基本依賴以下
<!-- thymeleaf模板-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <!-- springweb-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!-- spring security-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <!-- SpringBoot集成mybatis框架 -->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>${mybatis.spring.boot.starter.version}</version>
        </dependency>
        <!-- mysql驅動-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
application.yml配置
spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/security?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8&useSSL=true
    username: root
    password: 你的數據庫密碼
  thymeleaf:
    #是否緩存
    cache: false
    # 在構建URL時預先查看名稱的前綴
    prefix: classpath:/templates/
    # 構建URL時附加查看名稱的後綴
    suffix: .html
  #mybatis配置
mybatis:
  mapper-locations: classpath:mapper/*.xml
建立實體類以及基本的mapper,這裏使用easycode自動生成。
並對User實體類進行相應的改造,
/**
 * 系統用戶(User)實體類
 *
 * @author sdl
 * @since 2020-03-22 15:15:14
 */
public class User implements UserDetails, Serializable {
    private static final long serialVersionUID = -52166883900608909L;
    /**
    * ID
    */
    private Integer id;
    /**
    * 用戶名
    */
    private String username;
    /**
    * 密碼
    */
    private String password;
    
    其餘屬性省略...
    Getter and Setter省略...
    private List<Role> roles;

   //UserDetails的角色資源屬性集合
    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        List<SimpleGrantedAuthority> authorities = new ArrayList<>(roles.size());
        for (Role role : roles) {
            authorities.add(new SimpleGrantedAuthority(role.getName()));
        }
        return authorities;
    }
   // 帳號是否未過時
    @Override
    public boolean isAccountNonExpired() {
        return true;
    }
    // 帳號是否未鎖定
    @Override
    public boolean isAccountNonLocked() {
        return true;
    }
    // 帳號憑證是否未過時
    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }
    // 帳號是否可用,數據庫中定義了enabled字段
    @Override
    public boolean isEnabled() {
        return enabled;
    }
以及相應的dao層方法和mapper

daohtml

截屏2020-03-23下午3.31.06.png
mapper
截屏2020-03-23下午3.31.41.pngjava

相關文章
相關標籤/搜索