1. 程式人生 > 其它 >9、SpringBoot整合之SpringBoot整合SpringSecurity

9、SpringBoot整合之SpringBoot整合SpringSecurity

SpringBoot整合SpringSecurity

一、建立專案,選擇依賴

選擇Spring Web、Thymeleaf即可




二、在pom檔案中匯入相關依賴

<!-- 匯入SpringSecurity的啟動器 -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>

三、在resources\templates下準備頁面

目錄結構如下

index.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>index</title>
</head>
<body>
    <div  align="center">
        <h1>Welcome to index</h1>
        <div>
            <!-- 這裡的url是controller層的url -->
            <a th:href="@{/level_1/gotoHtml}">請求level_1</a>
        </div>

        <div>
            <a th:href="@{/level_2/gotoHtml}">請求level_2</a>
        </div>

        <div>
            <a th:href="@{/level_3/gotoHtml}">請求level_3</a>
        </div>

        <!-- 為稍後SpringSecurity的退出登入功能做準備 -->
        <a th:href="@{/logout}">登出</a>

    </div>

</body>
</html>

level_1.html、level_2.html、level_3.html內容相同,在此不多贅述,將數字部分替換即可

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>level_1</title>
</head>
<body>
    <div align="center">
        <h1>Welcome to level_1</h1>

        <a th:href="@{/}">回到index</a>

    </div>

</body>
</html>

四、構建controller層

package cn.byuan.controller;

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

@Controller
public class LevelAction {

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

//    這裡的url就是上面index.html中a標籤中出現的url    
    @RequestMapping("/level_1/gotoHtml")
    public String goToLevel1(){
        return "level_1";
    }

    @RequestMapping("/level_2/gotoHtml")
    public String goToLevel2(){
        return "level_2";
    }

    @RequestMapping("/level_3/gotoHtml")
    public String goToLevel3(){
        return "level_3";
    }
}

五、建立配置類,進行SpringSecurity的相關配置

SpringSecrity的兩大核心:認證(Authentication)授權(Authorization)

SpringSecurity的主要類

主要類 含義
@EnableWebSecurity 開啟WebSecurity
WebSecurityConfigurerAdapter 自定義security策略
AuthenticationManagerBuilder 自定義認證策略

建立配置類

package cn.byuan.config;

import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@EnableWebSecurity// 開啟WebSecurity模組
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    
}

游標移入花括號內,按下 ctrl + o

package cn.byuan.config;

import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

@EnableWebSecurity// 開啟WebSecurity模組
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    /*
     * 配置授權規則
     * */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
//        新增請求授權規則
        http.authorizeRequests()
                .antMatchers("/").permitAll()// 首頁所有人都可以訪問
                .antMatchers("/level_1/**").hasRole("vip1")// level_1下的所有請求, vip1使用者才可以訪問
                .antMatchers("/level_2/**").hasRole("vip2")// level_2下的所有請求, vip2使用者才可以訪問
                .antMatchers("/level_3/**").hasRole("vip3");// level_3下的所有請求, vip3使用者才可以訪問

        http.formLogin();// 開啟登入頁面, 即無許可權的話跳轉到登入頁面, 預設地址: /login, 這是為了有人直接訪問許可權範圍內某一url

        http.logout().logoutSuccessUrl("/");// 登出後跳轉到首頁

        http.rememberMe();// 開啟記住我功能, 預設儲存兩週, 底層使用cookie機制實現
    }

    /*
     * 配置認證規則
     *
     * 在新版本的SpringSecurity中新增了許多加密方法, 不使用加密的話就會出現異常
     * 這裡我們在記憶體中對使用者進行模擬, 真正的開發過程中會使用資料庫
     *
     * */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
                .passwordEncoder(new BCryptPasswordEncoder())
                .withUser("root").password(new BCryptPasswordEncoder().encode("root")).roles("vip1", "vip2", "vip3")
                .and()
                .withUser("zlf").password(new BCryptPasswordEncoder().encode("zlf")).roles("vip1", "vip2")
                .and()
                .withUser("user").password(new BCryptPasswordEncoder().encode("user")).roles("vip1");
    }
}

六、測試

開啟瀏覽器,輸入地址:http://localhost:8080/ 敲擊回車

點選:請求level_1,會自動跳轉至登入頁面,輸入賬號、密碼,點選Sign in

由於root擁有所有頁面的訪問許可權,因此訪問成功

點選回到index,點選退出登入,切換其他賬號進行測試


這次我們使用user賬號來訪問level_2,user只有level_1的訪問許可權

可以看到,如果沒有許可權訪問指定的url,那麼會報錯誤:403

原始碼地址:https://github.com/byuan98/springboot-integration/tree/master/test009_springboot_springsecurity