1. 程式人生 > 實用技巧 >Spring Security(1)入門體驗

Spring Security(1)入門體驗

Spring Security(1)入門體驗


Spring Security 和 Apache Shiro 都是安全框架,為Java應用程式提供身份認證和授權。本片文章將講述Security入門到專案實戰使用。其中包括簡單的登入和專案常用的許可權管理,許可權校驗有兩種方式、角色資源校驗、URL校驗,如果有一定基礎的可以想找解決辦法的可以直接跳過前面基礎直接尋找自己需要的解答內容。

二者區別

  1. Spring Security:重量級安全框架
  2. Apache Shiro:輕量級安全框架
    關於shiro的許可權認證與授權,(這個以後有需要再出一篇關於 Shiro 的內容)

SpringBoot整合Spring Security入門體驗

基於Spring Boot 2.1.8

1、引入Spring Security依賴

<!--新增Spring securit依賴-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>

2、新建一個controller 測試訪問

@RestController
public class IndexController {
    @GetMapping("/index")
    public String index() {
        return "Hello World ~";
    }
}

3、執行專案訪問:http://127.0.0.1:8080/index

溫馨小提示:在不進行任何配置的情況下,Spring Security 給出的預設使用者名稱為user 密碼則是專案在啟動執行時隨機生成的一串字串,會列印在控制檯,如下圖:




當我們訪問index首頁的時候,系統會預設跳轉到login頁面進行登入認證




認證成功之後才會跳轉到我們的index頁面





使用者密碼配置

除了上面Spring Security在不進行任何配置下預設給出的使用者user 密碼隨專案啟動生成隨機字串,我們還可以通過以下方式配置

1、springboot配置檔案中配置

spring:
 security:
   user:
     name: admin  # 使用者名稱
     password: 123456  # 密碼

2、java程式碼在記憶體中配置

新建 Security 核心配置類繼承 WebSecurityConfigurerAdapter

@Configuration
@EnableWebSecurity // 啟用Spring Security的Web安全支援
public class SecurityConfig extends WebSecurityConfigurerAdapter {
   /**
    * 將使用者設定在記憶體中
    * @param auth
    * @throws Exception
    */
   @Autowired
   public void config(AuthenticationManagerBuilder auth) throws Exception {
       // 在記憶體中配置使用者,配置多個使用者呼叫`and()`方法
       auth.inMemoryAuthentication()
           // 指定加密方式
           .passwordEncoder(passwordEncoder())
           // 設定訪問使用者名稱
           .withUser("admin")
           // 設定密碼
           .password(passwordEncoder().encode("123456"))
           // 使用者所擁有的角色許可權(注:這裡後續會用於許可權校驗)
           .roles("ADMIN")
           .and()
           // 如果想設定多個可以重複新增
           .withUser("test").password(passwordEncoder().encode("123456")).roles("USER");
   }
   @Bean
   public PasswordEncoder passwordEncoder() {
       // BCryptPasswordEncoder:Spring Security 提供的加密工具,可快速實現加密加鹽
       return new BCryptPasswordEncoder();
   }
}

3、從資料庫中獲取使用者賬號、密碼資訊

往往實際使用中會比上述情況複雜很多。
(動態新增使用者,繫結角色,角色繫結許可權資源等),這個留到文章後面鑑權內容再說。

登入處理 與 忽略攔截

最常用的簡單配置,相關程式碼都有註釋相信很容易理解

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
   /**
    * 登入處理
    * @param http
    * @throws Exception
    */
   @Override
   protected void configure(HttpSecurity http) throws Exception {
       
       //==========================================路徑相關配置start
       
       // antMatcher():配置需要處理的URL  authorizeRequests():為URL配置授權事項,例如是否需要進行身份驗證或僅某些角色可以訪問它等
        ExpressionUrlAuthorizationConfigurer<HttpSecurity>.ExpressionInterceptUrlRegistry registry = http.antMatcher("/**").authorizeRequests();
       
       // 標記只能在 伺服器本地ip[127.0.0.1或者localhost] 訪問`/home`介面,其他ip地址無法訪問
        registry.antMatchers("/home").hasIpAddress("127.0.0.1");

        // 標識訪問 `/index` 這個介面,需要具備`ADMIN`角色
        registry.antMatchers("/index").hasRole("ADMIN");

        // 允許匿名的url - 可理解為方形介面 - 多個介面使用,分割
        registry.antMatchers("/login", "/index").permitAll();

        // OPTIONS(選項):查詢適用於一個特定網址資源的通訊選擇。 在不需執行具體的涉及資料傳輸的動作情況下, 允許客戶端來確定與資源相關的選項以及 / 或者要求, 或是一個伺服器的效能
        registry.antMatchers(HttpMethod.OPTIONS, "/**").denyAll();

        // 其餘所有請求都需要認證
        registry.anyRequest().authenticated();
       
       //==========================================路徑相關配置end
       
       // 禁用CSRF 開啟跨域
        http.csrf().disable().cors();

        //配置HTTP基本身份認證
        http.httpBasic();
       
       // 設定登入認證頁面
       http.formLogin().loginPage("/login")
           // 登入後的處理介面 - 方式①
           .loginProcessingUrl("/user/login")
           // 自定義登陸使用者名稱和密碼屬性名,預設為 username和password
           .usernameParameter("username")
           .passwordParameter("password")
           // 登入成功後的處理器  - 方式② 可以通過處理器處理返回資訊(注:這裡可以單獨提出來寫一個類)
           //                .successHandler((req, resp, authentication) -> {
           //                    resp.setContentType("application/json;charset=utf-8");
           //                    PrintWriter out = resp.getWriter();
           //                    out.write("登入成功...");
           //                    out.flush();
           //                })
           // 配置登入失敗的回撥 同上可以提取
           .failureHandler((req, resp, exception) -> {
               resp.setContentType("application/json;charset=utf-8");
               PrintWriter out = resp.getWriter();
               out.write("登入失敗...");
               out.flush();
           })
           .logout().logoutUrl("/logout")
           // 配置登出成功的回撥
           .logoutSuccessHandler((req, resp, authentication) -> {
               resp.setContentType("application/json;charset=utf-8");
               PrintWriter out = resp.getWriter();
               out.write("登出成功...");
               out.flush();
           })
           // 和表單登入相關的介面都通過
           .permitAll()
   }
   /**
    * 忽略攔截
    * @param web
    * @throws Exception
    */
   @Override
   public void configure(WebSecurity web) throws Exception {
       // 設定攔截忽略url - 會直接過濾該url - 將不會經過Spring Security過濾器
       web.ignoring().antMatchers("/getUserInfo");
       // 設定攔截忽略資料夾,可以對靜態資源放行
       web.ignoring().antMatchers("/css/**", "/js/**");
   }
}






參考文獻以及版權宣告:

1、Spring Security(1) 入門體驗 作者:鄭清 採用協議:CC 4.0 BY-SA
原文連結:https://blog.csdn.net/qq_38225558/article/details/101754743