1. 程式人生 > 實用技巧 >【SpringBoot1.x】SpringBoot1.x 安全

【SpringBoot1.x】SpringBoot1.x 安全

SpringBoot1.x 安全

文章原始碼

環境搭建

SpringSecurity 是針對 Spring 專案的安全框架,也是 SpringBoot 底層安全模組預設的技術選型。他可以實現強大的 web 安全控制。對於安全控制,我們僅需引入 spring-boot-starter-security 模組,進行少量的配置,即可實現強大的安全管理。

登入 登出 認證 授權 許可權控制

應用程式的兩個主要區域是 “認證”“授權(或者訪問控制)”。這兩個主要區域是 SpringSecurity 的兩個目標。

通過繼承 WebSecurityConfigurerAdapter,可以自定義 Security 策略。使用 @EnableWebSecurity,開啟 WebSecurity 模式。

“認證”(Authentication),是建立一個它宣告的主體的過程(一個“主體”一般是指使用者,裝置或一些可以在你的應用程式中執行動作的其他系統)。

“授權”(Authorization),指確定一個主體是否允許在你的應用程式執行一個動作的過程。為了抵達需要授權的點,主體的身份已經由認證過程建立。

Thymeleaf 提供的 SpringSecurity 標籤支援,需要引入依賴:

        <!-- Thymeleaf 提供的 SpringSecurity 標籤支援 -->
        <dependency>
            <groupId>org.thymeleaf.extras</groupId>
            <artifactId>thymeleaf-extras-springsecurity4</artifactId>
        </dependency>

  • 首頁 welcome.html

    <!DOCTYPE html>
    <html xmlns:th="http://www.thymeleaf.org"
        xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Insert title here</title>
    </head>
    <body>
    <h1 align="center">歡迎光臨武林祕籍管理系統</h1>
    <div sec:authorize="!isAuthenticated()">
        <h2 align="center">遊客您好,如果想檢視武林祕籍 <a th:href="@{/userlogin}">請登入</a> </h2>
    </div>
    <div sec:authorize="isAuthenticated()">
        <h2 th:align="center">使用者:<span sec:authentication="name"></span>,角色:<span sec:authentication="principal.authorities"></span></h2>
        <form th:align="center" th:action="@{/logout}" method="post">
            <input type="submit" value="登出">
        </form>
    </div>
    
    <hr>
    
    <div sec:authorize="hasRole('VIP1')">
        <h3>普通武功祕籍</h3>
        <ul>
            <li><a th:href="@{/level1/1}">羅漢拳</a></li>
            <li><a th:href="@{/level1/2}">武當長拳</a></li>
            <li><a th:href="@{/level1/3}">全真劍法</a></li>
        </ul>
    </div>
    
    <div sec:authorize="hasRole('VIP2')">
        <h3>高階武功祕籍</h3>
        <ul>
            <li><a th:href="@{/level2/1}">太極拳</a></li>
            <li><a th:href="@{/level2/2}">七傷拳</a></li>
            <li><a th:href="@{/level2/3}">梯雲縱</a></li>
        </ul>
    </div>
    
    <div sec:authorize="hasRole('VIP3')">
        <h3>絕世武功祕籍</h3>
        <ul>
            <li><a th:href="@{/level3/1}">葵花寶典</a></li>
            <li><a th:href="@{/level3/2}">龜派氣功</a></li>
            <li><a th:href="@{/level3/3}">獨孤九劍</a></li>
        </ul>
    </div>
    
    </body>
    </html>
    
  • 登入頁 login.html

    <!DOCTYPE html>
    <html xmlns:th="http://www.thymeleaf.org">
    <head>
    <meta charset="UTF-8">
    <title>Insert title here</title>
    </head>
    <body>
        <h1 align="center">歡迎登陸武林祕籍管理系統</h1>
        <hr>
        <div align="center">
            <form th:action="@{/userlogin}" method="post">
                使用者名稱:<input name="user"/><br>
                密碼:<input name="pwd"><br/>
                <input type="checkbox" name="remember"> 記住我 <br>
                <input type="submit" value="登陸">
            </form>
        </div>
    </body>
    </html>
    
  • 自定義安全配置類 CustomSecurityConfig.java

    /**
    * @Author : parzulpan
    * @Time : 2021-01
    * @Desc : 自定義安全配置類
    */
    
    @EnableWebSecurity  // 開啟 WebSecurity 模式
    public class CustomSecurityConfig 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");
    
            // 開啟自動配置的登入功能,如果沒有登入或者沒有許可權就會來到登入頁面
            // 1. 訪問 /login 來到登入頁
            // 2. 重定向到 login?error 表示登入失敗
            // 3. ...
            // http.formLogin();
    
            // 指定自定義的登入頁
            // 1. 預設 post 形式,/login 代表處理登入
            // 2. 一旦定製 loginPage,那麼 loginPage 的 post 請求就是登入
            http.formLogin().usernameParameter("user").passwordParameter("pwd")
                    .loginPage("/userlogin");
    
            // 關閉 CSRF(Cross-site request forgery)跨站請求偽造
            // http.csrf().disable();
    
            // 開啟自動配置的登出功能
            // 1. 訪問 /logout 表示使用者登出,清空 session
            // 2. 登出成功,會自動重定向到 login?logout
            // 3. logoutSuccessUrl 登出成功,自動回到首頁
            http.logout().logoutSuccessUrl("/");
    
            // 開啟記住我功能
            // 1. 登入成功以後,將 cookie 發給瀏覽器儲存,以後訪問頁面會帶上這個 cookie,只要通過檢查就可以免登入
            // 2. 點選登出就會刪除 cookie
            http.rememberMe().rememberMeParameter("remember");
    
        }
    
        // 定製認證規則
        @Override
        protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
                .withUser("User01").password("123456").roles("VIP1", "VIP2")
                .and()
                .withUser("User02").password("123456").roles("VIP2", "VIP3")
                .and()
                .withUser("User03").password("123456").roles("VIP3", "VIP1");
        }
    }
    
  • 書籍控制類 KungfuController.java

    /**
    * @Author : parzulpan
    * @Time : 2021-01
    * @Desc : 書籍控制類
    */
    
    @Controller
    public class KungfuController {
        private final String PREFIX = "pages/";
    
        /**
            * 歡迎頁
            * @return
            */
        @GetMapping("/")
        public String index() {
            return "welcome";
        }
    
        /**
            * 登陸頁
            * @return
            */
        @GetMapping("/userlogin")
        public String loginPage() {
            return PREFIX+"login";
        }
    
        /**
            * level1頁面對映
            * @param path
            * @return
            */
        @GetMapping("/level1/{path}")
        public String level1(@PathVariable("path")String path) {
            return PREFIX+"level1/"+path;
        }
    
        /**
            * level2頁面對映
            * @param path
            * @return
            */
        @GetMapping("/level2/{path}")
        public String level2(@PathVariable("path")String path) {
            return PREFIX+"level2/"+path;
        }
    
        /**
            * level3頁面對映
            * @param path
            * @return
            */
        @GetMapping("/level3/{path}")
        public String level3(@PathVariable("path")String path) {
            return PREFIX+"level3/"+path;
        }
    }
    

總結和練習