天天看點

springsecurity自定義資料庫模型的認證與授權1. 引入依賴2. 資料庫準備3. 實作UserDetails4.啟動測試

部分控制器代碼參考Spring Security預設資料庫模型的認證于授權

1. 引入依賴

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <!--        其他spring-security依賴-->
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-web</artifactId>
            <version>5.7.3</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-config</artifactId>
            <version>5.7.3</version>
        </dependency>

        <!-- 資料庫依賴-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
            <version>2.7.3</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.30</version>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.24</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.2.2</version>
        </dependency>

        <!-- aop-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aop</artifactId>
            <version>5.3.23</version>
        </dependency>


        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </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>
           

2. 資料庫準備

create table users(
	id bigint(20) not null auto_increment,
	username varchar(50) not null,
	password varchar(60),
	enable tinyint(4) not null default 1 comment '使用者是否可用',
	roles text character set utf8 comment '使用者角色,多個角色之間用逗号隔開',
	primary key(id),
	key username (username)
);

insert into users(username, password, roles) values ('admin', '123', 'ROLE_ADMIN;ROLE_USER');
insert into users(username, password, roles) values ('user', '123', 'ROLE_USER');
           
使用者資訊和角色放在同一張表中,roles字段設定為text,多個角色之間通過逗号隔開,也可用通過分号等其他字元隔開。
  • 在入口類MapperScan指定mybatis要掃描的映射檔案目錄
    springsecurity自定義資料庫模型的認證與授權1. 引入依賴2. 資料庫準備3. 實作UserDetails4.啟動測試

3. 實作UserDetails

3.1 實作

xxx.xxx.config.WebSecurityConfig.java

package com.lzd.springsecuritydemo.config;

import jdk.nashorn.internal.runtime.logging.Logger;
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.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

/**
 * @author li
 * @date 2022年10月03日 16:12
 */

@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter  {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeHttpRequests()
                // 隻對ADMIN角色放行
                .antMatchers("/admin/api/**").hasRole("ADMIN")
                .antMatchers("/user/api/**").hasRole("USER")
                .antMatchers("/app/api/**").permitAll()
                .anyRequest().authenticated()
                .and()
                .formLogin().permitAll()
                .and()
                .csrf().disable();
    }
}

           

3.2 在pojo包下建立

User.java

類,繼承UserDetails

package com.lzd.springsecuritydemo.pojo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Collection;
import java.util.List;

/**
 * @author li
 * @date 2022年10月04日 16:53
 * @Description
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User implements UserDetails {
    private Long id;

    private String username;

    private String password;

    private String roles;

    private boolean enable;

    private List<GrantedAuthority> authorities;

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return this.authorities;
    }

    @Override
    public String getPassword() {
        return this.password;
    }

    @Override
    public String getUsername() {
        return this.username;
    }


    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return this.enable;
    }
}

           

實作UserDetails定義的幾個方法:

  • isAccountNonExpired、isAccountNonLocked、isCredentialsNonExpired暫時用不到,統一傳回true,否則會賬号異常。
  • isEnabled對映enable字段。
  • getAuthorities方法本身對應的是roles字段

3.3 在mapper下實作

UserMapper

接口

package com.lzd.springsecuritydemo.mapper;

import com.lzd.springsecuritydemo.pojo.User;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Component;

/**
 * @author: li
 * @date: 2022年10月04日 17:03
 * @description: TODO
 */

@Component
public interface UserMapper {
    @Select("select * from users where username=#{username}")
    User findByUserName(@Param("username") String username);
}

           

3.4 在service下編寫UserDetailsService

package com.lzd.springsecuritydemo.service;

import com.lzd.springsecuritydemo.mapper.UserMapper;
import com.lzd.springsecuritydemo.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author: li
 * @date: 2022年10月04日 17:06
 * @description: TODO
 */
@Service
public class MyUserDetailsService implements UserDetailsService {
    @Autowired
    private UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 從資料庫中查詢使用者
        User user = userMapper.findByUserName(username);
        if (user == null) {
            throw new UsernameNotFoundException("使用者不存在");
        }

        // AuthorityUtils.commaSeparatedStringToAuthorityList是spring security提供的 預設根據
        // 逗号分割權限字元集字元串切割成可用權限對象清單
        //user.setAuthorities(AuthorityUtils.commaSeparatedStringToAuthorityList(user.getRoles()));

        // 使用自定義的分隔方法
        user.setAuthorities(generateAuthorities(user.getRoles()));
        return user;
    }

    /**
     * 自行實作通過分号隔開權限集字元串
     * @param roles
     * @return
     */
    private List<GrantedAuthority> generateAuthorities(String roles) {
        List<GrantedAuthority> authorities = new ArrayList<>();
        if (roles != null && !"".equals(roles)) {
            String[] roleArray = roles.split(";");
            for (String role : roleArray) {
                // SimpleGrantedAuthority是GrantedAuthority是一個實作類
                authorities.add(new SimpleGrantedAuthority(role));
            }
        }
        return authorities;
    }
}

           

4.啟動測試