如何控制項目的訪問權限來保證項目安全?SpringBoot 集成 Spring Security 安全框架使用指南

安全框架

  • shiro
  • Spring Security
  • 應用程序的兩個主要區域:認證受權(這兩個主要區域是Spring Security的兩個目標)web

    • 認證(Authentication):spring

      • 創建一個聲明的主體過程
      • 一個[主體]通常是指[用戶],[設備]或一些能夠[在應用程序中執行動做的其它系統]
    • 受權(Authorization):瀏覽器

      • 訪問控制肯定一個主體是否容許在你的應用程序執行一個動做的過程
      • 爲了抵達須要受權的點,主體身份已經有認證過程的創建安全

        Spring Security

  • 針對Spring項目的安全框架,是Spring Boot底層安全模塊默認的技術選型
  • 能夠實現web安全控制,只須要引入spring-boot-starter-security依賴配置便可
  • Spring Security中的類:session

    • WebSecurityConfigurerAdapter: 自定義Security策略
    • AuthenticationManagerBuilder: 自定義認證策略
    • @EnableWebSecurity: 開啓WebSecurity模式框架

      1.引入spring-boot-starter-security依賴
      
      2.編寫SpringSecurity配置類
      2.1 定製請求的受權規則
      2.2 開啓自動配置的登陸功能(/login來到登陸頁;重慶向到/login?error表示登陸失敗)
      2.3 開啓自動配置的註銷功能(訪問/logout請求,表示用戶註銷並清空session;註銷成功返回/login?logout)
      2.4 開啓自動配置的記住密碼功能(http.rememberMe();)-登陸成功之後,將Cookie發送給瀏覽器保存,能夠實現記住密碼功能;點擊註銷會刪除Cookie,就沒有記住密碼功能
      默認post形式的/login表明處理登陸
      2.5定義認證規則
      @EnableSecurity
      public class MySecurityConfig extends WebSecurityConfigureAdapter{
      @Override
      protected void configure(HttpSecurity http) throws Exception{
          // 定製請求的受權規則
          http.authorizeRequest().antMatches("/").permitAll()
              .antMatches("/level/**").hasRole("VIP");
          // 開啓自動配置的登陸功能,若是沒有權限就會跳轉到登陸頁面
          http.formLogin().loginPage("/");    // 跳轉到自定義登陸頁
          http.logout().logoutSuccessUrl("/");    // 註銷成功返回首頁
          http.rememberMe().rememberMeParameter("remember");    // 開啓自動配置的記住密碼功能
      }
      @Override
      protected void configure(AuthenticationManagerBuilder auth) throws Exception{
          auth.inMemoryAuthentication().withUser("username").password("password").roles("role1","role2")
                                       .and()
                                       .withUser("username").password("password").roles("role1","role2")
      }
      
      
      3.控制請求的訪問權限
  • Thymeleaf Extras Springsecurity4
相關文章
相關標籤/搜索