SpringBoot:整合SpringSecurity


SpringBoot 整合 SpringSecurity;

用戶認證和授權、注銷及權限控制、記住我和登錄頁面定制。

SpringSecurity(安全)

搭建環境

版本: 先使用 SpringBoot 2.2.4.RELEASE

后面會切換到 SpringBoot 2.0.9.RELEASE

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

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-test</artifactId>
  <scope>test</scope>
  <exclusions>
    <exclusion>
      <groupId>org.junit.vintage</groupId>
      <artifactId>junit-vintage-engine</artifactId>
    </exclusion>
  </exclusions>
</dependency>

<!--thymeleaf模板-->
<dependency>
  <groupId>org.thymeleaf</groupId>
  <artifactId>thymeleaf-spring5</artifactId>
</dependency>

<dependency>
  <groupId>org.thymeleaf.extras</groupId>
  <artifactId>thymeleaf-extras-java8time</artifactId>
</dependency>

資料下載地址

1582794735287.png

編寫網頁對應的Controller:

package com.rainszj.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class RouterController {

    @RequestMapping({"/", "/index"})
    public String index() {
        return "index";
    }

    @RequestMapping("/toLogin")
    public String toLogin() {

        return "views/login";
    }

    @RequestMapping("/level1/{id}")
    public String level1(@PathVariable("id") int id) {

        System.out.println(id);

        return "views/level1/" + id;
    }

    @RequestMapping("/level2/{id}")
    public String level2(@PathVariable("id") int id) {

        return "views/level2/" + id;
    }

    @RequestMapping("/level3/{id}")
    public String level3(@PathVariable("id") int id) {

        return "views/level3/" + id;
    }
}

測試的時候,關閉 thymeleaf 的緩存

spring.thymeleaf.cache=false

訪問:http://localhost:8080,測試是否可以成功跳轉視圖!

1582794838586.png

簡介

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

記住幾個類:

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

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

認證(Authentication )

授權( Authorization)

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

Spring Security官網

官方文檔

使用

要使用它只需要在Spring Boot中導入Spring Security 的啟動器:

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

導入依賴后,我們來看看 @EnableWebSecurity這個注解

@Retention(value = java.lang.annotation.RetentionPolicy.RUNTIME)
@Target(value = { java.lang.annotation.ElementType.TYPE })
@Documented
@Import({ WebSecurityConfiguration.class,
      SpringWebMvcImportSelector.class,
      OAuth2ImportSelector.class })
@EnableGlobalAuthentication
@Configuration
public @interface EnableWebSecurity {

   /**
    * Controls debugging support for Spring Security. Default is false.
    * @return if true, enables debug support with Spring Security
    */
   boolean debug() default false;
}

從源碼中看出,加了@EnableWebSecurity注解的類本質上也是一個配置類!

從注釋中,可以看到它的用法:

1582791976362.png

要使用 Spring Security,只需要 添加 @EnableWebSecurity,並讓該類繼承WebSecurityConfigurerAdapter,重寫其中的 一些configure()方法即可

用戶認證和授權

我們新建一個文件夾:config,編寫一個類:SecurityConfig

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    // 授權
    @Override
    protected void configure(HttpSecurity http) throws Exception {

        // 鏈式編程
        // 請求權限的規則
        http.authorizeRequests()
                .antMatchers("/").permitAll()
                .antMatchers("/level1/**").hasRole("vip1")
                .antMatchers("/level2/**").hasRole("vip2")
                .antMatchers("/level3/**").hasRole("vip3")
                .and()
                .formLogin();

        // 沒有權限默認會到登錄頁面,需要開啟登錄的頁面
        // 默認會跳到 /login 請求中
        // http.formLogin();

    }

    /**
     * 認證
     * 需要密碼編碼:PasswordEncoder
     * 在 SpringSecurity 5.0+ 中新增了很多加密方法
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {

        // 這些數據正常應該從數據庫中讀取
        auth.inMemoryAuthentication()
                .withUser("rainszj").password("123456").roles("vip2", "vip3")
                .and()
                .withUser("root").password("123456").roles("vip1", "vip2", "vip3")
                .and()
                .withUser("guest").password("123456").roles("vip1");
    }

}

There is no PasswordEncoder mapped for the id "null"

必須要對密碼進行加密才能使用!

密碼編碼:PasswordEncoder

1582795163737.png

1582796074825.png

重寫該方法:protected void configure(AuthenticationManagerBuilder auth)

@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {

    // 這些數據正常應該從數據庫中讀取
    auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
            .withUser("rainszj").password(new BCryptPasswordEncoder().encode("123456")).roles("vip2", "vip3")
            .and()
            .withUser("root").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1", "vip2", "vip3")
            .and()
            .withUser("guest").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1");
}

OK!

關於這些要重寫的方法,具體如何操作,我們可以點擊WebSecurityConfigurerAdapter這個類中,里面有大量的注釋介紹如何重寫該方法!

例如:

/**
 * Used by the default implementation of {@link #authenticationManager()} to attempt
 * to obtain an {@link AuthenticationManager}. If overridden, the
 * {@link AuthenticationManagerBuilder} should be used to specify the
 * {@link AuthenticationManager}.
 *
 * <p>
 * The {@link #authenticationManagerBean()} method can be used to expose the resulting
 * {@link AuthenticationManager} as a Bean. The {@link #userDetailsServiceBean()} can
 * be used to expose the last populated {@link UserDetailsService} that is created
 * with the {@link AuthenticationManagerBuilder} as a Bean. The
 * {@link UserDetailsService} will also automatically be populated on
 * {@link HttpSecurity#getSharedObject(Class)} for use with other
 * {@link SecurityContextConfigurer} (i.e. RememberMeConfigurer )
 * </p>
 *
 * <p>
 * For example, the following configuration could be used to register in memory
 * authentication that exposes an in memory {@link UserDetailsService}:
 * </p>
 *
 * <pre>
 * &#064;Override
 * protected void configure(AuthenticationManagerBuilder auth) {
 *     auth
 *     // enable in memory based authentication with a user named
 *     // &quot;user&quot; and &quot;admin&quot;
 *     .inMemoryAuthentication().withUser(&quot;user&quot;).password(&quot;password&quot;).roles(&quot;USER&quot;).and()
 *           .withUser(&quot;admin&quot;).password(&quot;password&quot;).roles(&quot;USER&quot;, &quot;ADMIN&quot;);
 * }
 *
 * // Expose the UserDetailsService as a Bean
 * &#064;Bean
 * &#064;Override
 * public UserDetailsService userDetailsServiceBean() throws Exception {
 *     return super.userDetailsServiceBean();
 * }
 *
 * </pre>
 *
 * @param auth the {@link AuthenticationManagerBuilder} to use
 * @throws Exception
 */
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
   this.disableLocalConfigureAuthenticationBldr = true;
}

注銷及權限控制

Semantic UI

前端添加 注銷按鈕, http.logout() 默認會跳轉到:/logout 請求

1582798346674.png

<!--注銷-->
<a class="item" th:href="@{/logout}">
    <i class="sign-out icon"></i> 注銷
</a>

SecurityConfig中配置:

// 授權
@Override
protected void configure(HttpSecurity http) throws Exception {

    // 鏈式編程
    // 請求權限的規則
    http.authorizeRequests()
            .antMatchers("/").permitAll()
            .antMatchers("/level1/**").hasRole("vip1")
            .antMatchers("/level2/**").hasRole("vip2")
            .antMatchers("/level3/**").hasRole("vip3")
            .and()
            // 沒有權限默認會到登錄頁面,需要開啟登錄的頁面
            // /login
            // http.formLogin();
            .formLogin();
    
// 簡單的可定制化的登出
// .logout().deleteCookies("remove").invalidateHttpSession(false);
// .logoutUrl("/custom-logout").logoutSuccessUrl("/logout-success");

    // 注銷,開啟了注銷功能,跳到首頁,默認會跳到 /login
    http.logout().logoutSuccessUrl("/");

}

訪問:http://localhost:8080/login 登錄

點擊 注銷,會跳轉到首頁,OK!

thymeleaf 整合 Spring Secuirty:

在 Spring Boot 2.2.4.RELEASE 版本中使用:

<!--thymeleaf Spring Security整合包-->
<dependency>
    <groupId>org.thymeleaf.extras</groupId>
    <artifactId>thymeleaf-extras-springsecurity5</artifactId>
    <version>3.0.4.RELEASE</version>
</dependency>

sec 的命名空間:

xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity5"

在Spring Boot 2.0.9.RELEASE 版本中使用:

<!--thymeleaf Spring Security整合包-->
<dependency>
    <groupId>org.thymeleaf.extras</groupId>
    <artifactId>thymeleaf-extras-springsecurity4</artifactId>
    <version>3.0.4.RELEASE</version>
</dependency>

sec 的命名空間:

xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4"

現在切換到:SpringBoot 2.0.9.RELEASE

引入 thymeleaf-extras-springsecurity4 版本的命名空間后,IDEA會有提示,但引入thymeleaf-extras-springsecurity5 后,沒有提示,很奇怪!

在index.html 中做如下修改:

<div class="right menu">
  <!--如果未登錄,顯示登錄-->
  <div sec:authorize="!isAuthenticated()">
    <a class="item" th:href="@{/toLogin}">
      <i class="address card icon"></i> 登錄
    </a>
  </div>

  <!--如果已登錄,顯示用戶名和注銷-->
  <div sec:authorize="isAuthenticated()">
    <!--用戶名-->
    <a class="item">
      用戶名:<span sec:authentication="name"></span>
      &nbsp;&nbsp;
      角色:<span sec:authentication="principal.authorities"></span>
    </a>
  </div>

  <div sec:authorize="isAuthenticated()">
    <!--注銷-->
    <a class="item" th:href="@{/logout}">
      <i class="sign-out icon"></i> 注銷
    </a>
  </div>

目前了解到的有關SpringSecurity的標簽屬性有以下幾個:

  • sec:authorize="isAuthenticated()"
    判斷用戶是否已經登陸認證,引號內的參數必須是isAuthenticated()
  • sec:authentication=“name”
    獲得當前用戶的用戶名,引號內的參數必須是name
  • sec:authorize=“hasRole(‘role’)”
    判斷當前用戶是否擁有指定的權限。引號內的參數為權限的名稱。
  • sec:authentication="principal.authorities"
    獲得當前用戶的全部角色,引號內的參數必須是principal.authorities

1582804639651.png

注意:注銷失敗可能的原因

在 SpringBoot 2.2.4.RELEASE 中,點擊注銷功能時,有個確認按鈕,內部使用了post方法,而 SpringBoot 2.0.9.RELEASE 中沒有提示按鈕,默認使用了get方式,get 請求不安全,明文傳輸,為防止網站攻擊,Spring Boot默認會開啟csrf(跨站請求偽造),想要注銷成功,需要在授權功能中關閉 csrf 這個功能!

// 授權
@Override
protected void configure(HttpSecurity http) throws Exception {
  	// ......
  
  	// 關閉 csrf 功能
  	http.csrf().disable();
}
<!--菜單根據用戶的角色動態實現-->
<div class="column" sec:authorize="hasRole('vip1')">
    <div class="ui raised segment">
        <div class="ui">
            <div class="content">
                <h5 class="content">Level 1</h5>
                <hr>
                <div><a th:href="@{/level1/1}"><i class="bullhorn icon"></i> Level-1-1</a></div>
                <div><a th:href="@{/level1/2}"><i class="bullhorn icon"></i> Level-1-2</a></div>
                <div><a th:href="@{/level1/3}"><i class="bullhorn icon"></i> Level-1-3</a></div>
            </div>
        </div>
    </div>
</div>

<div class="column" sec:authorize="hasRole('vip2')">
    <div class="ui raised segment">
        <div class="ui">
            <div class="content">
                <h5 class="content">Level 2</h5>
                <hr>
                <div><a th:href="@{/level2/1}"><i class="bullhorn icon"></i> Level-2-1</a></div>
                <div><a th:href="@{/level2/2}"><i class="bullhorn icon"></i> Level-2-2</a></div>
                <div><a th:href="@{/level2/3}"><i class="bullhorn icon"></i> Level-2-3</a></div>
            </div>
        </div>
    </div>
</div>

<div class="column" sec:authorize="hasRole('vip3')">
    <div class="ui raised segment">
        <div class="ui">
            <div class="content">
                <h5 class="content">Level 3</h5>
                <hr>
                <div><a th:href="@{/level3/1}"><i class="bullhorn icon"></i> Level-3-1</a></div>
                <div><a th:href="@{/level3/2}"><i class="bullhorn icon"></i> Level-3-2</a></div>
                <div><a th:href="@{/level3/3}"><i class="bullhorn icon"></i> Level-3-3</a></div>
            </div>
        </div>
    </div>
</div>

1582806234029.png

登錄:http://localhost:8080/login
1582806263748.png

1582806198691.png

1582806219114.png

記住我及登錄頁面定制

如果不適用記住我功能,當我們在瀏覽器端輸入用戶名和密碼登錄,關閉瀏覽器時,會話結束,再次打開瀏覽器訪問時,需要再次輸入用戶名和密碼登錄!

而記住我功能,本質上是一個 Cookie,而Spring Security 的記住我功能使用了Session和Cookie。

  • [ ] 記住我功能:

默認自帶的

要使用Spring Security默認的登錄表單實現 記住我 功能,只需在授權方法(configure(HttpSecurity http))中,添加一行代碼即可:

// 開啟記住我功能,cookie默認保存兩周
http.rememberMe();

1582807965050.png

1582808127798.png

自定義

要使用自定義的表單實現記住我功能:

前端:

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

在原有remeberMe()方法中指定前端的 name 參數即可,名稱可以任意寫:

// 開啟記住我功能,cookie默認保存兩周,需要自定義接收前端的參數
http.rememberMe().rememberMeParameter("remberme");

1582808944187.png

1582808966518.png

登錄頁面定制:

開啟默認登錄頁面

要使用Spring Security 默認的登錄頁面,在授權方法中添加一行代碼即可!

// 沒有權限默認會到登錄頁面,需要開啟登錄的頁面
// 會默認跳轉到 /login 請求
http.formLogin();

自定義登錄頁面

方式一

同樣在 configure(HttpSecurity http),授權方法中添加如下,但是 loginPage() 的請求要和表單提交的 action 請求地址一致!

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

前端登錄的 form 表單:

<form th:action="@{/toLogin}" method="post">
    <div class="field">
        <label>Username</label>
        <div class="ui left icon input">
            <input type="text" placeholder="Username" name="username">
            <i class="user icon"></i>
        </div>
    </div>
    <div class="field">
        <label>Password</label>
        <div class="ui left icon input">
            <input type="password" name="password">
            <i class="lock icon"></i>
        </div>
    </div>
    <div class="field">
        <input type="checkbox" name="remberme"> 記住我
    </div>

    <input type="submit" class="ui blue submit button"/>
</form>

方式二

需要加上實際登錄時處理的URL:loginProcessingUrl("/login");

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

前端:

<form th:action="@{/login}" method="post">
    <div class="field">
        <label>Username</label>
        <div class="ui left icon input">
            <input type="text" placeholder="Username" name="username">
            <i class="user icon"></i>
        </div>
    </div>
    <div class="field">
        <label>Password</label>
        <div class="ui left icon input">
            <input type="password" name="password">
            <i class="lock icon"></i>
        </div>
    </div>
    <div class="field">
        <input type="checkbox" name="remberme"> 記住我
    </div>

    <input type="submit" class="ui blue submit button"/>
</form>

這里的表單參數能夠提交成功,是因為在formLogin()的源碼中,默認的用戶名和密碼的name參數默認是:username 和 password

1582809792570.png

假設我們前端提交參數名不是 username 和 password 的呢?

現在將用戶名改為:name 密碼改為:pwd,再試試,發現提交失敗!,走到了 error 請求

1582809930622.png

那么該如何修改呢?通過看 formLogin() 方法的注釋我們也能得知,只需指定提交的參數名即可

http.formLogin()
        .loginPage("/toLogin")
        .loginProcessingUrl("/login")
        .usernameParameter("name")
        .passwordParameter("pwd");

測試即可,搞定!


免責聲明!

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



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