SpringBoot安全管理--(二)基於數據庫的認證


簡介:

  上篇文章向讀者介紹的認證數據都是定義在內存中的,在真實項目中,用戶的基本信息以及角色等都存儲在數據庫中,因此需要從數據庫中獲取數據進行認證。

開始:

首先建表並且插入數據:

 

 

 

 

 

 

 

 

 

 

 

 pom.xml

   <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.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.2</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.10</version>
        </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>

 

 

 創建實體類:

public class User implements UserDetails {
    private Integer id;
    private String username;
    private String password;
    private Boolean enabled;
    private Boolean locked;
    private List<Role> roles;
  
//獲取當前用戶對象所具有的所有角色信息 @Override
public Collection<? extends GrantedAuthority> getAuthorities() { List<SimpleGrantedAuthority> authorities = new ArrayList<>(); for (Role 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 !locked; }
//當前賬戶密碼是否過期 @Override
public boolean isCredentialsNonExpired() { return true; }
//判斷當前賬戶是否可用 @Override
public boolean isEnabled() { return enabled; } //省略getter/setter }
public class Role {
    private Integer id;
    private String name;
    private String nameZh;
    //省略getter/setter

}

Service:

  定義UserService實現UserDetailsService接口,並實現該接口中的loadUserByUsemame方法,該方法的參數就是用戶登錄時輸入的用戶名,通過用戶名去數據庫中查找用戶,如果沒有查找到用戶,就拋出一個賬戶不存在的異常,如果查找到了用戶,就繼續查找該用戶所具有的角色信息,並將獲取到的user對象返回,再由系統提供DaoAuthenticationProvider 類去比對密碼是否正確。

@Service
public class UserService implements UserDetailsService {
    @Autowired
    UserMapper userMapper;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { User user = userMapper.loadUserByUsername(username); if (user == null) { throw new UsernameNotFoundException("賬戶不存在!"); } user.setRoles(userMapper.getUserRolesByUid(user.getId())); return user; } }

Mapper:

@Mapper
public interface UserMapper {
    User loadUserByUsername(String username);
    List<Role> getUserRolesByUid(Integer id);
}
<mapper namespace="org.sang.security02.mapper.UserMapper">
    <select id="loadUserByUsername" resultType="org.sang.security02.model.User">
        select * from user where username=#{username}
    </select>
    <select id="getUserRolesByUid" resultType="org.sang.security02.model.Role">
        select * from role r,user_role ur where r.id=ur.rid and ur.uid=#{id}
    </select>
</mapper>

配置SpringSecurity

角色繼承:

 在上面定義了三種角色,但是這三種角色之間不具備任何關系,一般來說角色之間是有關系的,例如ROLE admin -般既具有admin的權限,又具有user的權限。那么如何配置

這種角色繼承關系呢?在Spring Security 中只需要開發者提供一-個RoleHierarchy即可。

  以上面的案例為例,假設ROLE_dba是終極大Boss,具有所有的權限,ROLE_admin具有ROLE _user 的權限,ROL_user 則是一個公共角色,即ROLE_admin繼承ROLE_user、 ROLE_dba繼承ROLE_ admin, 要描述這種繼承關系,只需要開發者在Spring Security 的配置類中提供一個RoleHierarchy即可,代碼如下:

@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    UserService userService;
@Bean RoleHierarchy roleHierarchy() { RoleHierarchyImpl roleHierarchy
= new RoleHierarchyImpl(); String hierarchy = "ROLE_dba > ROLE_admin ROLE_admin > ROLE_user"; roleHierarchy.setHierarchy(hierarchy); return roleHierarchy; } @Bean PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(userService);      //沒有將用戶存在內存中,而是從數據庫中取出來 } @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .withObjectPostProcessor(new ObjectPostProcessor<FilterSecurityInterceptor>() { @Override public <O extends FilterSecurityInterceptor> O postProcess(O object) { object.setSecurityMetadataSource(cfisms()); object.setAccessDecisionManager(cadm()); return object; } }) .and() .formLogin() .loginProcessingUrl("/login").permitAll() .and() .csrf().disable(); } @Bean CustomFilterInvocationSecurityMetadataSource cfisms() { return new CustomFilterInvocationSecurityMetadataSource(); } @Bean CustomAccessDecisionManager cadm() { return new CustomAccessDecisionManager(); } }

 Controller:

@RestController
public class HelloController {
    @GetMapping("/admin/hello")
    public String admin() {
        return "hello admin";
    }
    @GetMapping("/db/hello")
    public String dba() {
        return "hello dba";
    }
    @GetMapping("/user/hello")
    public String user() {
        return "hello user";
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM