最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

SpringBoot2.0 整合 SpringSecurity 框架實(shí)現(xiàn)用戶權(quán)限安全管理方法

 更新時(shí)間:2019年07月17日 09:00:43   作者:知了一笑  
Spring Security是一個(gè)能夠?yàn)榛赟pring的企業(yè)應(yīng)用系統(tǒng)提供聲明式的安全訪問控制解決方案的安全框架。這篇文章主要介紹了SpringBoot2.0 整合 SpringSecurity 框架,實(shí)現(xiàn)用戶權(quán)限安全管理 ,需要的朋友可以參考下

一、Security簡(jiǎn)介

1、基礎(chǔ)概念

Spring Security是一個(gè)能夠?yàn)榛赟pring的企業(yè)應(yīng)用系統(tǒng)提供聲明式的安全訪問控制解決方案的安全框架。它提供了一組可以在Spring應(yīng)用上下文中配置的Bean,充分利用了Spring的IOC,DI,AOP(面向切面編程)功能,為應(yīng)用系統(tǒng)提供聲明式的安全訪問控制功能,減少了為安全控制編寫大量重復(fù)代碼的工作。

2、核心API解讀

1)、SecurityContextHolder

最基本的對(duì)象,保存著當(dāng)前會(huì)話用戶認(rèn)證,權(quán)限,鑒權(quán)等核心數(shù)據(jù)。SecurityContextHolder默認(rèn)使用ThreadLocal策略來存儲(chǔ)認(rèn)證信息,與線程綁定的策略。用戶退出時(shí),自動(dòng)清除當(dāng)前線程的認(rèn)證信息。

初始化源碼:明顯使用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,權(quán)限列表,通常是代表權(quán)限的字符串集合;
2)、getCredentials,密碼,認(rèn)證之后會(huì)移出,來保證安全性;
3)、getDetails,請(qǐng)求的細(xì)節(jié)參數(shù);
4)、getPrincipal, 核心身份信息,一般返回UserDetails的實(shí)現(xiàn)類。

3)、UserDetails

封裝了用戶的詳細(xì)的信息。

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

4)、UserDetailsService

實(shí)現(xiàn)該接口,自定義用戶認(rèn)證流程,通常讀取數(shù)據(jù)庫(kù),對(duì)比用戶的登錄信息,完成認(rèn)證,授權(quán)。

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

5)、AuthenticationManager

認(rèn)證流程頂級(jí)接口。可以通過實(shí)現(xiàn)AuthenticationManager接口來自定義自己的認(rèn)證方式,Spring提供了一個(gè)默認(rèn)的實(shí)現(xiàn),ProviderManager。

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

二、與SpringBoot2整合

1、流程描述
1)、三個(gè)頁(yè)面分類,page1、page2、page3
2)、未登錄授權(quán)都不可以訪問
3)、登錄后根據(jù)用戶權(quán)限,訪問指定頁(yè)面
4)、對(duì)于未授權(quán)頁(yè)面,訪問返回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 {
  /**
   * 權(quán)限配置
   */
  @Override
  protected void configure(HttpSecurity http) throws Exception {
    // 配置攔截規(guī)則
    http.authorizeRequests().antMatchers("/").permitAll()
         .antMatchers("/page1/**").hasRole("LEVEL1")
         .antMatchers("/page2/**").hasRole("LEVEL2")
         .antMatchers("/page3/**").hasRole("LEVEL3");
    // 配置登錄功能
    http.formLogin().usernameParameter("user")
        .passwordParameter("pwd")
        .loginPage("/userLogin");
    // 注銷成功跳轉(zhuǎn)首頁(yè)
    http.logout().logoutSuccessUrl("/");
    //開啟記住我功能
    http.rememberMe().rememberMeParameter("remeber");
  }
  /**
   * 自定義認(rèn)證數(shù)據(jù)源
   */
  @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();
  }
  /*
   * 硬編碼幾個(gè)用戶
  @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、認(rèn)證流程

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

5、測(cè)試接口

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

6、登錄界面

這里要和Security的配置文件相對(duì)應(yīng)。

<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
碼云地址:知了一笑
https://gitee.com/cicadasmile/middle-ware-parent

總結(jié)

以上所述是小編給大家介紹的SpringBoot2.0 整合 SpringSecurity 框架實(shí)現(xiàn)用戶權(quán)限安全管理方法,希望對(duì)大家有所幫助,如果大家有任何疑問請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)腳本之家網(wǎng)站的支持!
如果你覺得本文對(duì)你有幫助,歡迎轉(zhuǎn)載,煩請(qǐng)注明出處,謝謝!

相關(guān)文章

  • SpringBoot項(xiàng)目集成依賴Mybatis步驟

    SpringBoot項(xiàng)目集成依賴Mybatis步驟

    在本篇文章中小編給大家分享了關(guān)于SpringBoot項(xiàng)目如何集成依賴Mybatis的相關(guān)知識(shí)點(diǎn)內(nèi)容,有興趣的朋友們學(xué)習(xí)下。
    2019-06-06
  • Java基礎(chǔ)之異常處理詳解

    Java基礎(chǔ)之異常處理詳解

    異??赡苁窃诔绦驁?zhí)行過程中產(chǎn)生的,也可能是程序中throw主動(dòng)拋出的。本文主要給大家介紹了Java中異常處理的相關(guān)資料,文中通過實(shí)例代碼介紹的非常詳細(xì),需要的朋友可以參考下
    2023-04-04
  • 淺談mybatis中SQL語(yǔ)句給boolean類型賦值問題

    淺談mybatis中SQL語(yǔ)句給boolean類型賦值問題

    這篇文章主要介紹了淺談mybatis中SQL語(yǔ)句給boolean類型賦值問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧
    2020-11-11
  • 解決mybatis plus報(bào)錯(cuò)Invalid bound statement (not found):問題

    解決mybatis plus報(bào)錯(cuò)Invalid bound statement 

    在使用MyBatis時(shí)遇到InvalidBoundStatement異常,常因多個(gè)MapperScan配置沖突或者包掃描路徑設(shè)置錯(cuò)誤,解決方法包括保留一個(gè)MapperScan聲明、檢查jar包沖突、確保命名空間和掃描路徑正確,使用@TableId注解指定主鍵
    2024-11-11
  • 創(chuàng)建java多線程程序

    創(chuàng)建java多線程程序

    Java 給多線程編程提供了內(nèi)置的支持。一條線程指的是進(jìn)程中一個(gè)單一順序的控制流,一個(gè)進(jìn)程中可以并發(fā)多個(gè)線程,每條線程并行執(zhí)行不同的任務(wù)。希望本篇文章能夠給你帶來幫助
    2021-06-06
  • MyBatis數(shù)組與集合判斷空問題

    MyBatis數(shù)組與集合判斷空問題

    這篇文章主要介紹了MyBatis數(shù)組與集合判斷空問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2023-02-02
  • 如何對(duì)Mysql數(shù)據(jù)表查詢出來的結(jié)果進(jìn)行排序

    如何對(duì)Mysql數(shù)據(jù)表查詢出來的結(jié)果進(jìn)行排序

    這篇文章主要介紹了如何對(duì)Mysql數(shù)據(jù)表查詢出來的結(jié)果進(jìn)行排序問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2023-08-08
  • Spring security 自定義過濾器實(shí)現(xiàn)Json參數(shù)傳遞并兼容表單參數(shù)(實(shí)例代碼)

    Spring security 自定義過濾器實(shí)現(xiàn)Json參數(shù)傳遞并兼容表單參數(shù)(實(shí)例代碼)

    這篇文章主要介紹了Spring security 自定義過濾器實(shí)現(xiàn)Json參數(shù)傳遞并兼容表單參數(shù),本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2021-01-01
  • java實(shí)現(xiàn)多客戶聊天功能

    java實(shí)現(xiàn)多客戶聊天功能

    這篇文章主要為大家詳細(xì)介紹了java實(shí)現(xiàn)多客戶聊天功能,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2021-08-08
  • 簡(jiǎn)單了解Java程序運(yùn)行整體流程

    簡(jiǎn)單了解Java程序運(yùn)行整體流程

    這篇文章主要介紹了簡(jiǎn)單了解Java程序運(yùn)行整體流程,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2020-07-07

最新評(píng)論

印江| 兴安盟| 漯河市| 徐闻县| 微博| 饶阳县| 沈丘县| 宾川县| 嘉鱼县| 南溪县| 南和县| 大荔县| 建瓯市| 中卫市| 城步| 礼泉县| 大方县| 通州市| 隆德县| 息烽县| 桦南县| 千阳县| 左权县| 海阳市| 锦州市| 宜丰县| 杭州市| 抚州市| 和林格尔县| 永昌县| 个旧市| 来安县| 阳新县| 章丘市| 蓬溪县| 永定县| 万山特区| 河曲县| 湘潭县| 徐州市| 亳州市|