异步身份验证

此示例演示了如何为 htmx 实现异步身份验证令牌流。

我们将在这里使用的技术将利用您可以使用 htmx:confirm 事件延迟请求的事实。

我们首先有一个按钮,该按钮在检索到身份验证令牌之前不应该发出请求。

  <button hx-post="/example" hx-target="next output">
    An htmx-Powered button
  </button>
  <output>
    --
  </output>

接下来,我们将添加一些脚本以使用 auth promise(由库返回)。

<script>
  // auth is a promise returned by our authentication system

  // await the auth token and store it somewhere
  let authToken = null;
  auth.then((token) => {
    authToken = token
  })
  
  // gate htmx requests on the auth token
  htmx.on("htmx:confirm", (e)=> {
    // if there is no auth token
    if(authToken == null) {
      // stop the regular request from being issued
      e.preventDefault() 
      // only issue it once the auth promise has resolved
      auth.then(() => e.detail.issueRequest()) 
    }
  })

  // add the auth token to the request as a header
  htmx.on("htmx:configRequest", (e)=> {
    e.detail.headers["AUTH"] = authToken
  })
</script>

我们在这里使用全局变量,但您可以使用 localStorage 或您想用来将身份验证令牌传达给 htmx:configRequest 事件的任何首选机制。

有了这段代码,htmx 不会发出请求,直到 auth promise 已解决。