iT邦幫忙

1

VScode 開發應用系統專案(8- 4) - Spring Boot Security 設定與認證(測試驗證)

  • 分享至 

  • xImage
  •  

Spring Boot 安全認證測試

概述

前面有介紹了 Spring Boot Security 設定與認證 (DB/AD/JWT/Oauth2)等,這裡說明測試方式與測試範例,因為不是每個專案都需要提供這麼所有的認證,後續應用於系統專案時可以參考與再調整,例如前後端分離的系統,也許後端只需要JWT認證就可以 (另如 Vue + Spring Boot),另外需要進一步了解系統流程,建議熟悉Debug方式執行系統,很多地方我也是使用Debug以及 Logger來除錯及找出問題處理與解決方法。

確認systemEnvReader.getProperty取得資料

example: systemEnvReader.getProperty("LOGIN_PAGE_URL", SecurityConstants.LOGIN_PAGE_URL);

  • systemEnvReader.getProperty 優先使用環境變數設定,若沒有則使用Default值,
  • 另有些Default值設定於靜態變數(例如SecurityConstants)物件內,有些直接 HardCode。
  • 因專案環境(開發/測試)等而需要不同的設定值,所以變數性質,調整以Active Profile區分設定於環境變數或靜態變數,通常不建議HardCode,但確定不會調整的常變數則無妨HardCode。

** 確認系統Spring Boot的啟動**

  • t.l.w.base.security.WebSecurityConfig:
  • Configuring OAuth2 Login with /callback endpoint...
  • Setting OAuth2 redirection endpoint to /callback
  • ✓ Setting OAuth2SuccessHandler
  • Configuring OAuth2 Login with /callback endpoint...
  • ✓ Setting OAuth2SuccessHandler
  • ✓ Setting OAuth2UserService
  • ✓ Setting OAuth2FailureHandler
  • ✓ CustomAuthenticationProvider added to AuthenticationManager for form login

https://ithelp.ithome.com.tw/upload/images/20251210/20139477xma5F9AcYt.png

測試時,建議清除瀏覽器的瀏覽紀錄,有些測試畫面不會呈現
https://ithelp.ithome.com.tw/upload/images/20251210/20139477YT2Sb6bXGA.png

**增加測試SysUserProfile資料(DataBase 認證用)

位置:src/test/java/tw/lewishome/webapp/database/primary/repository/SysUserProfileRepositoryTest

**省略部分是,若有參考Spring Boot資料庫設計與存取-單一 Key URL: https://ithelp.ithome.com.tw/articles/10398629 ,應該已經有此測試程式,只需增加testCreateSurityUser Method即可)

package tw.lewishome.webapp.database.primary.repository;

import static org.junit.jupiter.api.Assertions.*;

import java.util.List;
import java.util.Optional;

import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.TestPropertySource;

import tw.lewishome.webapp.base.utility.common.SM3Utils;
import tw.lewishome.webapp.database.primary.entity.SysUserProfileEntity;

/**
 * SysUserProfileRepository Integration Tests
 * 
 * Tests for SysUserProfileRepository using real repository with
 * 
 * @BeforeEach to add test data and @AfterEach to clean up.
 *
 * @author lewis
 */
@SpringBootTest
@TestPropertySource(locations = "classpath:application.properties")
public class SysUserProfileRepositoryTest {

    @Autowired
    private SysUserProfileRepository sysUserProfileRepository;

    private SysUserProfileEntity testEntity;
 
    //**省略  */![https://ithelp.ithome.com.tw/upload/images/20251210/20139477bjhqciPCuB.png](https://ithelp.ithome.com.tw/upload/images/20251210/20139477bjhqciPCuB.png)

    @Test
    void testCreateSurityUser(){
        // Create CreateSurity test entity
        testEntity = new SysUserProfileEntity();
        SysUserProfileEntity.DataKey dataKey1 = new SysUserProfileEntity.DataKey();
        dataKey1.setUserId("TEST_USER");
        testEntity.setDataKey(dataKey1);
        testEntity.setUserName("Test User One");
        testEntity.setUserEmail("testuser1@example.com");
        testEntity.setUserDept("IT Department");
        testEntity.setUserExt("1234");
        String password = SM3Utils.encrypt("Password1");
        testEntity.setUserPassword(password);
        testEntity.setUserLevel("5");
        testEntity.setUserLastAuth("0");
        testEntity.setUserMenuLayoutTop(true);
        testEntity.setUserIsVaild(true);
        testEntity.setExpired(false);
        testEntity.setLocked(false);
        sysUserProfileRepository.saveAndFlush(testEntity);
    }
}

執行測試產生資料
https://ithelp.ithome.com.tw/upload/images/20251210/20139477Y6X9p7iZKf.png

登入測試

登入畫面

https://ithelp.ithome.com.tw/upload/images/20251210/201394773IJct9PfEM.png!

登入成功

https://ithelp.ithome.com.tw/upload/images/20251210/201394772VnaCNkKhB.png

1. AD 登入(必需設定AD Server並可以連線)

https://ithelp.ithome.com.tw/upload/images/20251210/201394778uObkhtr1Z.png

2. MEM登入(程式固定測試適用)

預設三組 BBB:BBB, CCC:CCC AAA:AAA

    // Memory User, password map
    private Map<String, String> MapUserAuth = Stream
            .of(new String[][] { { "AAA", "AAA" }, { "BBB", "BBB" }, { "CCC", "CCC" }
            }).collect(Collectors.toMap(data -> data[0], data -> data[1]));

登入成功訊息

https://ithelp.ithome.com.tw/upload/images/20251210/20139477i6PEm2bYVa.png

登入成功後新增 DB (ast_auth)
https://ithelp.ithome.com.tw/upload/images/20251210/20139477NDmeZWS77L.png


2. DB 登入成功訊息

https://ithelp.ithome.com.tw/upload/images/20251210/20139477C1ItXP1urV.png


4. Google

系統導向 Google登入認證畫面
https://ithelp.ithome.com.tw/upload/images/20251210/20139477AQtmDelZSO.png

Google登入認證
https://ithelp.ithome.com.tw/upload/images/20251210/20139477yyW91KrMru.png

Google登入授權畫面
https://ithelp.ithome.com.tw/upload/images/20251210/20139477CgkdkWSSU4.png

Google登入成功後訊息
https://ithelp.ithome.com.tw/upload/images/20251210/20139477JPGMtvMENb.png

Google 登入成功後新增 DB (last_auth)
https://ithelp.ithome.com.tw/upload/images/20251210/20139477z1QZ3wN8SS.png


5. Github

系統導向 Github 登入認證畫面
https://ithelp.ithome.com.tw/upload/images/20251210/20139477OcIiT0IzmA.png


Github 登入成功後訊息
https://ithelp.ithome.com.tw/upload/images/20251210/20139477CX2OnHWLoU.png

Github 登入成功後新增 DB (last_auth) 這裡因為 Google Email與 Github Email相同,所以會覆蓋。

https://ithelp.ithome.com.tw/upload/images/20251210/20139477auBGSw4pEI.png


JWT Token And API

  • 確認有安裝REST Client 以及系統已啟動。
    https://ithelp.ithome.com.tw/upload/images/20251210/20139477lCME8Xmps3.png

  • 增加測試GetSystemApiTest.http(JWT 認證Rest Client script),注意:副檔名為 .http

位置:src/test/java/tw/lewishome/webapp/base/security/jwttoken/GetSystemApiTest.http

# @name tokenrequest failed
POST http://localhost:8080/jwtAuth/signin 
content-type: application/json

{
    "username":"AAA",
    "password":"AAAX"
}

###
# @name tokenrequest2
POST http://localhost:8080/jwtAuth/signin 
content-type: application/json

{
    "username":"AAA",
    "password":"AAA"
}

###
### Role: API_USERX exception test
@token = {{tokenrequest2.response.body.bearerToken}}

# @name api
POST http://localhost:8080/systemApiTest/test/TESTJOB/START
Authorization: {{token}}
Content-Type: application/json

{}

### Role: API_USER test OK
# @name api2
POST http://localhost:8080/systemApiTest/test3/TESTJOB/START
Authorization: {{token}}
Content-Type: application/json

{}
  • Vscode 開啟檔案,REST Client自動會顯示 "Send Request"(紅框)

https://ithelp.ithome.com.tw/upload/images/20251210/20139477cQdXb0v4Xb.png

  • 執行 @name tokenrequest failed 的 Send Request

http: 403

https://ithelp.ithome.com.tw/upload/images/20251210/20139477iljztamzPN.png

執行紀錄(CustomAuthenticationProvider)

https://ithelp.ithome.com.tw/upload/images/20251210/20139477LtAejK6lmy.png

  • 執行 @name tokenrequest2 的 Send Request

http: 200 以及 取得 bearerToken

https://ithelp.ithome.com.tw/upload/images/20251210/20139477c3uIrZMtHN.png

執行紀錄(CustomAuthenticationProvider)
[CustomAuthenticationProvider] authenticate returning token principal= AAA , authenticated= true

https://ithelp.ithome.com.tw/upload/images/20251210/20139477sEm3YdvI3M.png

  • 執行 @name api 的 Send Request

http: 302

https://ithelp.ithome.com.tw/upload/images/20251210/20139477z58ZS4x15a.png

執行紀錄(CustomAuthenticationProvider)
Resolved [org.springframework.security.authorization.AuthorizationDeniedException: Access Denied]

https://ithelp.ithome.com.tw/upload/images/20251210/20139477dXKQsmO04M.png

  • 執行 @name api2 的 Send Request
    http: 200

https://ithelp.ithome.com.tw/upload/images/20251210/201394777eEAYuK4vm.png

Method 執行結果(test JobId = TESTJOB & func Value ==> START)
https://ithelp.ithome.com.tw/upload/images/20251210/201394771b6cr9cJ9I.png


圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言