如何在Suave用户中存储数据?

时间:2016-09-23 23:27:36

标签: f# suave

我有一个处理OAuth回调请求的Web部件。

从API获取访问令牌和用户ID之后,我想将其存储在会话状态中。但是当在后续请求中阅读会话时,我只会看到" Suave.Auth"键。

以下是OAuth回调的网络部分:

path "/oauth" >=> context (fun ctx ->
        let req = ctx.request
        match (req.queryParam "code", req.queryParam "error") with
        | Choice1Of2 code, _ ->
            let id = completeOAuth code
            Authentication.authenticated Session false
            >=> Writers.setUserData "user-id" id
            >=> Redirection.redirect "/view"
        | _, Choice1Of2 error -> RequestErrors.UNAUTHORIZED error)

如何确保" user-id"在这个之后的其他请求会话中的值是什么?

1 个答案:

答案 0 :(得分:2)

Writers.setUserData将数据存储在地图中,该地图仅在请求期间存在。

要跨请求存储数据,您需要使用statefulForSession这样的数据。

let app = 
  statefulForSession >=> context (fun x ->
    match HttpContext.state x with
    | None ->
      // restarted server without keeping the key; set key manually?
      let msg = "Server Key, Cookie Serialiser reset, or Cookie Data Corrupt, "
      + "if you refresh the browser page, you'll have gotten a new cookie."
      OK msg
    | Some store ->
      match store.get "counter" with
      | Some y ->
        store.set "counter" (y + 1) >=> OK (sprintf "Hello %d time(s)" (y + 1))
      | None ->
        store.set "counter" 1 >=> OK "First time")