SpringBoot2.0 整合 SpringSecurity 框架,實現用戶權限安全管理

本文源碼:GitHub·點這裏 || GitEE·點這裏

一、Security簡介

1、基礎概念

Spring Security是一個能夠爲基於Spring的企業應用系統提供聲明式的安全訪問控制解決方案的安全框架。它提供了一組可以在Spring應用上下文中配置的Bean,充分利用了Spring的IOC,DI,AOP(面向切面編程)功能,爲應用系統提供聲明式的安全訪問控制功能,減少了爲安全控制編寫大量重複代碼的工作。

2、核心API解讀

1)、SecurityContextHolder

最基本的對象,保存着當前會話用戶認證,權限,鑑權等核心數據。SecurityContextHolder默認使用ThreadLocal策略來存儲認證信息,與線程綁定的策略。用戶退出時,自動清除當前線程的認證信息。

初始化源碼:明顯使用ThreadLocal線程。

private static void initialize() {
    if (!StringUtils.hasText(strategyName)) {
        strategyName = "MODE_THREADLOCAL";
    }
    if (strategyName.equals("MODE_THREADLOCAL")) {
        strategy = new ThreadLocalSecurityContextHolderStrategy();
    } else if (strategyName.equals("MODE_INHERITABLETHREADLOCAL")) {
        strategy = new InheritableThreadLocalSecurityContextHolderStrategy();
    } else if (strategyName.equals("MODE_GLOBAL")) {
        strategy = new GlobalSecurityContextHolderStrategy();
    } else {
        try {
            Class<?> clazz = Class.forName(strategyName);
            Constructor<?> customStrategy = clazz.getConstructor();
            strategy = (SecurityContextHolderStrategy)customStrategy.newInstance();
        } catch (Exception var2) {
            ReflectionUtils.handleReflectionException(var2);
        }
    }
    ++initializeCount;
}

2)、Authentication

源代碼

public interface Authentication extends Principal, Serializable {
    Collection<? extends GrantedAuthority> getAuthorities();
    Object getCredentials();
    Object getDetails();
    Object getPrincipal();
    boolean isAuthenticated();
    void setAuthenticated(boolean var1) throws IllegalArgumentException;
}

源碼分析

1)、getAuthorities,權限列表,通常是代表權限的字符串集合;
2)、getCredentials,密碼,認證之後會移出,來保證安全性;
3)、getDetails,請求的細節參數;
4)、getPrincipal, 核心身份信息,一般返回UserDetails的實現類。

3)、UserDetails

封裝了用戶的詳細的信息。

public interface UserDetails extends Serializable {
    Collection<? extends GrantedAuthority> getAuthorities();
    String getPassword();
    String getUsername();
    boolean isAccountNonExpired();
    boolean isAccountNonLocked();
    boolean isCredentialsNonExpired();
    boolean isEnabled();
}

4)、UserDetailsService

實現該接口,自定義用戶認證流程,通常讀取數據庫,對比用戶的登錄信息,完成認證,授權。

public interface UserDetailsService {
    UserDetails loadUserByUsername(String var1) throws UsernameNotFoundException;
}

5)、AuthenticationManager

認證流程頂級接口。可以通過實現AuthenticationManager接口來自定義自己的認證方式,Spring提供了一個默認的實現,ProviderManager。

public interface AuthenticationManager {
    Authentication authenticate(Authentication var1) throws AuthenticationException;
}

二、與SpringBoot2整合

1、流程描述

1)、三個頁面分類,page1、page2、page3
2)、未登錄授權都不可以訪問
3)、登錄後根據用戶權限,訪問指定頁面
4)、對於未授權頁面,訪問返回403:資源不可用

2、核心依賴

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

3、核心配置

/**
 * EnableWebSecurity註解使得SpringMVC集成了Spring Security的web安全支持
 */
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    /**
     * 權限配置
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // 配置攔截規則
        http.authorizeRequests().antMatchers("/").permitAll()
                 .antMatchers("/page1/**").hasRole("LEVEL1")
                 .antMatchers("/page2/**").hasRole("LEVEL2")
                 .antMatchers("/page3/**").hasRole("LEVEL3");
        // 配置登錄功能
        http.formLogin().usernameParameter("user")
                .passwordParameter("pwd")
                .loginPage("/userLogin");
        // 註銷成功跳轉首頁
        http.logout().logoutSuccessUrl("/");
        //開啓記住我功能
        http.rememberMe().rememberMeParameter("remeber");
    }
    /**
     * 自定義認證數據源
     */
    @Override
    protected void configure(AuthenticationManagerBuilder builder) throws Exception{
        builder.userDetailsService(userDetailService())
                .passwordEncoder(passwordEncoder());
    }
    @Bean
    public UserDetailServiceImpl userDetailService (){
        return new UserDetailServiceImpl () ;
    }
    /**
     * 密碼加密
     */
    @Bean
    public BCryptPasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }
    /*
     * 硬編碼幾個用戶
    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
                .withUser("spring").password("123456").roles("LEVEL1","LEVEL2")
                .and()
                .withUser("summer").password("123456").roles("LEVEL2","LEVEL3")
                .and()
                .withUser("autumn").password("123456").roles("LEVEL1","LEVEL3");
    }
    */
}

4、認證流程

@Service
public class UserDetailServiceImpl implements UserDetailsService {
    @Resource
    private UserRoleMapper userRoleMapper ;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 這裏可以捕獲異常,使用異常映射,拋出指定的提示信息
        // 用戶校驗的操作
        // 假設密碼是數據庫查詢的 123
        String password = "$2a$10$XcigeMfToGQ2bqRToFtUi.sG1V.HhrJV6RBjji1yncXReSNNIPl1K";
        // 假設角色是數據庫查詢的
        List<String> roleList = userRoleMapper.selectByUserName(username) ;
        List<GrantedAuthority> grantedAuthorityList = new ArrayList<>() ;
        /*
         * Spring Boot 2.0 版本踩坑
         * 必須要 ROLE_ 前綴, 因爲 hasRole("LEVEL1")判斷時會自動加上ROLE_前綴變成 ROLE_LEVEL1 ,
         * 如果不加前綴一般就會出現403錯誤
         * 在給用戶賦權限時,數據庫存儲必須是完整的權限標識ROLE_LEVEL1
         */
        if (roleList != null && roleList.size()>0){
            for (String role : roleList){
                grantedAuthorityList.add(new SimpleGrantedAuthority(role)) ;
            }
        }
        return new User(username,password,grantedAuthorityList);
    }
}

5、測試接口

@Controller
public class PageController {
    /**
     * 首頁
     */
    @RequestMapping("/")
    public String index (){
        return "home" ;
    }
    /**
     * 登錄頁
     */
    @RequestMapping("/userLogin")
    public String loginPage (){
        return "pages/login" ;
    }
    /**
     * page1 下頁面
     */
    @PreAuthorize("hasAuthority('LEVEL1')")
    @RequestMapping("/page1/{pageName}")
    public String onePage (@PathVariable("pageName") String pageName){
        return "pages/page1/"+pageName ;
    }
    /**
     * page2 下頁面
     */
    @PreAuthorize("hasAuthority('LEVEL2')")
    @RequestMapping("/page2/{pageName}")
    public String twoPage (@PathVariable("pageName") String pageName){
        return "pages/page2/"+pageName ;
    }
    /**
     * page3 下頁面
     */
    @PreAuthorize("hasAuthority('LEVEL3')")
    @RequestMapping("/page3/{pageName}")
    public String threePage (@PathVariable("pageName") String pageName){
        return "pages/page3/"+pageName ;
    }
}

6、登錄界面

這裏要和Security的配置文件相對應。

<div align="center">
    <form th:action="@{/userLogin}" method="post">
        用戶名:<input name="user"/><br>
        密&nbsp;&nbsp;&nbsp;碼:<input name="pwd"><br/>
        <input type="checkbox" name="remeber"> 記住我<br/>
        <input type="submit" value="Login">
    </form>
</div>

三、源代碼地址

GitHub·地址
https://github.com/cicadasmile/middle-ware-parent
GitEE·地址
https://gitee.com/cicadasmile/middle-ware-parent

SpringBoot2.0 整合 SpringSecurity 框架,實現用戶權限安全管理

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章