共用方式為


在數據 API 產生器中使用工作階段內容實作資料列層級安全性

使用 SQL 的 工作階段內容 功能,在資料 API 產生器中實作資料列層級安全性。

必要條件

  • 現有的 SQL Server 和資料庫。
  • 數據 API 產生器 CLI。 安裝 CLI
  • 資料庫用戶端 (SQL Server Management Studio、Azure Data Studio 等 )

Create SQL 資料表和數據

Create 此範例案例中要使用的虛構數據數據表。

  1. 使用您慣用的用戶端或工具連線到 SQL 資料庫。

  2. Create 名為、idcategoryrevenueusername 資料行的Revenues數據表。

    DROP TABLE IF EXISTS dbo.Revenues;
    
    CREATE TABLE dbo.Revenues(
        id int PRIMARY KEY,  
        category varchar(max) NOT NULL,  
        revenue int,  
        username varchar(max) NOT NULL  
    );
    GO
    
  3. 將四個範例書籍數據列插入 Revenues 數據表中。

    INSERT INTO dbo.Revenues VALUES
        (1, 'Book', 5000, 'Oscar'),  
        (2, 'Comics', 10000, 'Oscar'),  
        (3, 'Journals', 20000, 'Hannah'),  
        (4, 'Series', 40000, 'Hannah')
    GO
    
  4. 使用簡單的 SELECT * 查詢來測試您的數據。

    SELECT * FROM dbo.Revenues
    
  5. 建立名為 RevenuesPredicate 的函式。 此函式會根據目前的會話內容來篩選結果。

    CREATE FUNCTION dbo.RevenuesPredicate(@username varchar(max))
    RETURNS TABLE
    WITH SCHEMABINDING
    AS RETURN SELECT 1 AS fn_securitypredicate_result
    WHERE @username = CAST(SESSION_CONTEXT(N'name') AS varchar(max));
    
  6. 使用函式 Create 名為 RevenuesSecurityPolicy 的安全策略。

    CREATE SECURITY POLICY dbo.RevenuesSecurityPolicy
    ADD FILTER PREDICATE dbo.RevenuesPredicate(username)
    ON dbo.Revenues;
    

執行工具

執行 Data API builder (DAB) 工具來產生組態檔和單一實體。

  1. Create 設定為 true 時的新組--set-session-context態。

    dab init \
        --database-type mssql \
        --connection-string "<sql-connection-string>" \
        --set-session-context true
    
  2. 為數據表新增名為 revenuedbo.Revenues 的新實體。

    dab add revenue \
        --source "dbo.Revenues" \
        --permissions "anonymous:read"
    
  3. 啟動資料 API 產生器工具。

    dab start
    
  4. 流覽至 http://localhost:5000/api/revenue 端點。 觀察未傳回任何數據。 發生此行為的原因是未設定會話內容,且沒有任何記錄符合篩選述詞。

在 SQL 中測試

直接在 SQL 中測試篩選和述詞,以確保其運作正常。

  1. 使用您慣用的用戶端或工具再次連線到 SQL Server。

  2. 執行 , sp_set_session_context 將會話內容的 name 宣告手動設定為靜態值 Oscar

    EXEC sp_set_session_context 'name', 'Oscar';
    
  3. 執行一般 SELECT * 查詢。 觀察結果是否使用述詞自動篩選。

    SELECT * FROM dbo.Revenues;