SpringBoot整合SpringSecurity


SpringBoot整合SpringSecurity

1. 認識SpringSecurity

Spring Security 是針對Spring項目的安全框架,也是Spring Boot底層安全模塊默認的技術選型,他可以實現強大的Web安全控制,對於安全控制,我們僅需要引入spring-boot-starter-security 模塊,進行少量的配置,即可實現強大的安全管理!

記住幾個類:

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

Spring Security的兩個主要目標是 “認證” 和 “授權”(訪問控制)。

“認證”(Authentication)

身份驗證是關於驗證您的憑據,如用戶名/用戶ID和密碼,以驗證您的身份。

身份驗證通常通過用戶名和密碼完成,有時與身份驗證因素結合使用。

“授權” (Authorization)

授權發生在系統成功驗證您的身份后,最終會授予您訪問資源(如信息,文件,數據庫,資金,位置,幾乎任何內容)的完全權限。

這個概念是通用的,而不是只在Spring Security 中存在。

2. 認證和授權

目前,我們的測試環境,是誰都可以訪問的,我們使用 Spring Security 增加上認證和授權的功能

1、引入 Spring Security 模塊

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

2、編寫 Spring Security 配置類

參考官網:https://spring.io/projects/spring-security

查看我們自己項目中的版本,找到對應的幫助文檔:

https://docs.spring.io/spring-security/site/docs/5.3.2.RELEASE/reference/html5 #servlet-applications 8.16.4

@EnableWebSecurity
public class Config extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .apply(customDsl())
                .flag(true)
                .and()
            ...;
    }
}
@EnableWebSecurity // 開啟WebSecurity模式
public class SecurityConfig extends WebSecurityConfigurerAdapter {

   @Override
   protected void configure(HttpSecurity http) throws Exception {
       
  }
}

3、定制請求的授權規則

@Override
protected void configure(HttpSecurity http) throws Exception {
   // 定制請求的授權規則
   // 首頁所有人可以訪問
   http.authorizeRequests().antMatchers("/").permitAll()
  .antMatchers("/vip1/**").hasRole("vip1")
  .antMatchers("/vip2/**").hasRole("vip2")
  .antMatchers("/vip3/**").hasRole("vip3");
}

4、測試一下:發現除了首頁都進不去了!因為我們目前沒有登錄的角色,因為請求需要登錄的角色擁有對應的權限才可以!

5、在configure()方法中加入以下配置,開啟自動配置的登錄功能!

// 開啟自動配置的登錄功能
// /login 請求來到登錄頁
// /login?error 重定向到這里表示登錄失敗
http.formLogin();

6、測試一下:發現,沒有權限的時候,會跳轉到登錄的頁面!

7、查看剛才登錄頁的注釋信息;

我們可以定義認證規則,重寫configure(AuthenticationManagerBuilder auth)方法

//定義認證規則
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
   
   //在內存中定義,正常因該再數據庫取....
   auth.inMemoryAuthentication()
          .withUser("MapleLeaf").password("123456").roles("vip2","vip3")
          .and()
          .withUser("root").password("123456").roles("vip1","vip2","vip3")
          .and()
          .withUser("guest").password("123456").roles("vip1","vip2");
}

8、測試,我們可以使用這些賬號登錄進行測試!發現會報錯!

There is no PasswordEncoder mapped for the id “null”

9、原因,我們要將前端傳過來的密碼進行某種方式加密,否則就無法登錄,修改代碼

//定義認證規則
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
   //Spring security 5.0中新增了多種加密方式,也改變了密碼的格式。
   //要想我們的項目還能夠正常登陸,需要修改一下configure中的代碼。我們要將前端傳過來的密碼進行某種方式加密
   //spring security 官方推薦的是使用bcrypt加密方式。
   
   auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
          .withUser("maple").password(newBCryptPasswordEncoder().encode("123456")).roles("vip2","vip3")
          .and()
          .withUser("root").password(newBCryptPasswordEncoder().encode("123456")).roles("vip1","vip2","vip3")
          .and()
          .withUser("guest").password(newBCryptPasswordEncoder().encode("123456")).roles("vip1","vip2");
}

10、測試,發現,登錄成功,並且每個角色只能訪問自己認證下的規則!搞定

3、權限控制和注銷

1、開啟自動配置的注銷的功能

//定制請求的授權規則
@Override
protected void configure(HttpSecurity http) throws Exception {
   //....
   //開啟自動配置的注銷的功能
   // /logout 注銷請求
   //http.logout() //注銷后默認跳轉到登錄頁
   // .logoutSuccessUrl("/"); 注銷成功來到首頁
	http.logout().logoutSuccessUrl("/");
}

2、我們可以去測試一下,登錄成功后點擊注銷(/logout),發現注銷完畢會跳轉到首頁!

4、記住我

現在的情況,我們只要登錄之后,關閉瀏覽器,再登錄,就會讓我們重新登錄,但是很多網站的情況,就是有一個記住密碼的功能,這個該如何實現呢?很簡單

1、開啟記住我功能

//定制請求的授權規則
@Override
protected void configure(HttpSecurity http) throws Exception {
//。。。。。。。。。。。
   //記住我
   http.rememberMe();
}

2、我們再次啟動項目測試一下,發現登錄頁多了一個記住我功能,我們登錄之后關閉 瀏覽器,然后重新打開瀏覽器訪問,發現用戶依舊存在!

5、定制登錄頁

現在這個登錄頁面都是spring security 默認的,怎么樣可以使用我們自己寫的Login界面呢?

1、在剛才的登錄頁配置后面指定 loginpage

http.formLogin().loginPage("/login");

2、然后前端也需要指向我們自己定義的 login請求

<a class="item" href="login">
   <i class="address card icon"></i> 登錄
</a>

注意login.html 請求提交的方式必須為post:

3、請求提交上來,我們還需要驗證處理,怎么做呢?我們可以查看formLogin()方法的源碼!我們配置接收登錄的用戶名和密碼的參數!

http.formLogin()
  .usernameParameter("username")
  .passwordParameter("palssword")
  .loginPage("/login")
  .loginProcessingUrl("/login"); // 登陸表單提交請求

4、在登錄頁增加記住我的多選框

<input type="checkbox" name="remember"> 記住我

5、后端驗證處理!

//定制記住我的參數!
http.rememberMe().rememberMeParameter("remember");

6、測試,OK

6、完整配置代碼

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

   //定制請求的授權規則
   @Override
   protected void configure(HttpSecurity http) throws Exception {

       http.authorizeRequests().antMatchers("/").permitAll()
      .antMatchers("/vip1/**").hasRole("vip1")
      .antMatchers("/vip2/**").hasRole("vip2")
      .antMatchers("/vip3/**").hasRole("vip3");


       //開啟自動配置的登錄功能:如果沒有權限,就會跳轉到登錄頁面!
           // /login 請求來到登錄頁
           // /login?error 重定向到這里表示登錄失敗
       http.formLogin()
          .usernameParameter("username")
          .passwordParameter("password")
          .loginPage("/login")
          .loginProcessingUrl("/login"); // 登陸表單提交請求

       //開啟自動配置的注銷的功能
           // /logout 注銷請求
           // .logoutSuccessUrl("/"); 注銷成功來到首頁

       http.csrf().disable();//關閉csrf功能:跨站請求偽造,默認只能通過post方式提交logout請求
       http.logout().logoutSuccessUrl("/");

       //記住我
       http.rememberMe().rememberMeParameter("remember");
  }

   //定義認證規則
   @Override
   protected void configure(AuthenticationManagerBuilder auth) throws Exception {
       //在內存中定義,也可以在jdbc中去拿....
       //Spring security 5.0中新增了多種加密方式,也改變了密碼的格式。
       //要想我們的項目還能夠正常登陸,需要修改一下configure中的代碼。我們要將前端傳過來的密碼進行某種方式加密
       //spring security 官方推薦的是使用bcrypt加密方式。

       auth.inMemoryAuthentication().passwordEncoder(newBCryptPasswordEncoder())
              .withUser("maple").password(newBCryptPasswordEncoder().encode("123456")).roles("vip2","vip3")
              .and()
              .withUser("root").password(newBCryptPasswordEncoder().encode("123456")).roles("vip1","vip2","vip3")
              .and()
              .withUser("guest").password(newBCryptPasswordEncoder().encode("123456")).roles("vip1","vip2");
  }
}


免責聲明!

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



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