簡體   English   中英

如何添加屬性進行記錄?

[英]How to add properties to record?

我想要

  1. 從 http 請求中提取 jwt
  2. 從 jwt 獲得索賠
  3. 將聲明添加到命令 model

像下面

let middleware<'a> handler next (ctx: HttpContext) =
    task {
        let token = ctx.Request.Headers.["Authorization"].ToString()
        match token with
        | Bearer token ->
            let claims = getClaims token
            let! command = ctx.BindJsonAsync<'a>()
            // how to add claims to command?
            return! handler command next ctx

        | _ ->
            return! RequestErrors.unauthorized "Bearer" "Commerce" authenticationError next ctx
    }

我如何進行第三步?

我可以在這里想到 4 個選項。

  1. 您可以將 JWT 授權屬性添加到命令 model 中,並在調用BindJsonAsync然后填充它時避免綁定它們。 這是我最不喜歡的方法,因為您最終會得到可以由發送 model 的人設置的屬性。

  2. 您可以使用匿名記錄向您的記錄類型添加其他屬性。 這種方法您需要知道可能導致問題的命令類型,因為看起來您正在使用通用 model 綁定。 它還使得跨二進制邊界傳遞類型變得更加困難。

type CommandHandler = { Command : string; Entity : int }
let command = { Command = "Update"; Entity = 1 }
let authorisedCommand = {| command with AuthToken = "ey ===" |}
  1. 您可以創建一個新類型,它是您用於 model 綁定的類型的副本,除了附加屬性,但這意味着您需要知道要復制的固定類型,並且您還需要復制所有屬性。
type CommandHandlerModel = { Command : string; Id : int }
type AuthorisedCommandHandlerModel = { Command : string; Id : int }
let commandHandler = { CommandHandlerModel.Command = "Update"; Id = 1 }
let authedCommandHandler = { AuthporosedCommandHandlerModel.Command = "Update"; Id = 1 }
  1. 我可能會采取的方法是將您的命令包裝成這樣的新類型:
type CommandHandlerModel = { Command : string; Id : int }
type AuthorisedCommandHandlerModel<'a> = { CommandModel : 'a; AuthToken : string }
let! command = ctx.BindJsonAsync<'a>()
let authedCommand = { CommandModel = command; AuthToken = claims }

我覺得這種組合方法是解決問題的一種更慣用的方法,也是我過去使用過的一種方法

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM