詳解springboot springsecuroty中的註銷和權限控制問題

上篇文章給大傢介紹瞭springboot對接第三方微信授權及獲取用戶的頭像和昵稱等等

1 賬戶註銷

1.1 在SecurityConfig中加入開啟註銷功能的代碼

src/main/java/com/lv/config/SecurityConfig.java

package com.lv.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;
//AOP : 攔截器!
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    //授權
    @Override
    public void configure(HttpSecurity http) throws Exception {
        //首頁所有人都可以訪問,功能頁隻有對應的有權限的人才能訪問
        //請求授權的規則~(鏈式編程)
        http.authorizeRequests()
                .antMatchers("/").permitAll()
                .antMatchers("/level1/**").hasRole("vip1")
                .antMatchers("/level2/**").hasRole("vip2")
                .antMatchers("/level3/**").hasRole("vip3");
        //沒有權限默認會跳轉到登錄頁,需要開啟登錄頁面
        http.formLogin();
        //註銷,開啟瞭註銷功能,跳到首頁
        http.logout().logoutSuccessUrl("/");
        //防止跨站工具, get,post
        http.csrf().disable();//關閉csrf功能,註銷失敗可能的原因
    }
    //認證,springboot 2.1.x 可以直接使用
    //密碼編碼:PasswordEncoder
    //在Spring Security 5.0+ 新增瞭很多加密方法~
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //這些數據正常應該從數據庫中讀
        auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
                .withUser("lv").password(new BCryptPasswordEncoder().encode("123456")).roles("vip2","vip3")
                .and()
                .withUser("root").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1","vip2","vip3")
                .withUser("guest").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1");
}

1.2 在index.html 添加註銷的按鈕

src/main/resources/templates/index.html

<!--登錄註銷-->
<div class="right menu">
    <div>
        <a class="item" th:href="@{/toLogin}">
            <i class="address card icon"></i>登錄
        </a>
    </div>
    <div>
        <a class="item" th:href="@{/logout}">
            <i class="sign-out icon"></i>註銷
        </a>
    </div>
</div>

1.3 啟動項目測試

訪問登錄頁面,登錄 guest 賬戶,該賬戶可以訪問 level1的頁面

登錄成功後,點擊 level1的鏈接,成功跳轉到 level 頁面,然後點擊註銷按鈕

彈回到首頁,再次點擊點擊 level1 頁面

跳轉到瞭登錄頁面

說明賬戶註銷成功

2 權限控制

2.1 導入springsecurity和thymeleaf的整合依賴

pom.xml

<!-- springSecurity和thymeleaf整合包 -->
<dependency>
    <groupId>org.thymeleaf.extras</groupId>
    <artifactId>thymeleaf-extras-springsecurity4</artifactId>
    <version>3.0.2.RELEASE</version>
</dependency>

2.2 springboot版本降級

pom.xml

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.0.9.RELEASE</version>
    <relativePath/> <!-- lookup parent from repository -->
</parent>

必須將springboot的版本降到2.0.9以下,否則 sec:authorize="isAuthenticated()" 不會生效.版本降低後,需要手動導入junit依賴,否則測試類會報錯

<dependency>
    <groupId>org.junit.jupiter</groupId>
    <artifactId>junit-jupiter</artifactId>
    <version>RELEASE</version>
    <scope>test</scope>
</dependency>

2.3 引入約束

在index.html的頭文件中添加springsecurity和thymeleaf的整合約束

src/main/resources/templates/index.html

<html xmlns:th="http://www.thymeleaf.org"
      xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4">

2.4 修改頁面代碼

主要修改兩部分,一部分是登錄狀態下顯示用戶名,和註銷按鈕,未登錄顯示登錄按鈕 通過 sec:authorize="isAuthenticated()" 實現.另一部分是根據登錄用戶的權限顯示不同的頁面菜單,通過 sec:authorize="hasRole('vip1')" 實現.

src/main/resources/templates/index.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"
      xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <title>首頁</title>
    <!--semantic-ui-->
    <link href="https://cdn.bootcss.com/semantic-ui/2.4.1/semantic.min.css" rel="stylesheet">
    <link th:href="@{/qinjiang/css/qinstyle.css}" rel="stylesheet">
</head>
<body>

<!--主容器-->
<div class="ui container">
    <div class="ui segment" id="index-header-nav" th:fragment="nav-menu">
        <div class="ui secondary menu">
            <a class="item"  th:href="@{/index}">首頁</a>
            <!--登錄註銷-->
            <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>
                    </a>
                </div>
                <div sec:authorize="isAuthenticated()">
                    <a class="item" th:href="@{/logout}">
                        <i class="sign-out icon"></i>註銷
                    </a>
                </div>
            </div>
        </div>
    </div>
    <div class="ui segment" style="text-align: center">
        <h3>Spring Security Study by 秦疆</h3>
    </div>
    <div>
        <br>
        <div class="ui three column stackable grid">
            <!--菜單根據用戶的角色動態實現-->
            <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>
        </div>
    </div>
</div>
<script th:src="@{/qinjiang/js/jquery-3.1.1.min.js}"></script>
<script th:src="@{/qinjiang/js/semantic.min.js}"></script>
</body>
</html>

2.5 重啟程序測試

未登錄頁面

登錄 lv 用戶的頁面

登錄 geust 用戶的頁面

登錄 root 用戶的頁面

頁面顯示都不同,權限控制成功實現

到此這篇關於springboot-springsecuroty 註銷和權限控制的文章就介紹到這瞭,更多相關springboot註銷和權限控制內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: