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


免責聲明!

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



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