异步身份验证

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

¥This example shows how to implement an an async auth token flow for htmx.

我们将在此处使用的技术将利用你可以使用 htmx:confirm 事件延迟请求的事实。

¥The technique we will use here will take advantage of the fact that you can delay requests using the htmx:confirm event.

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

¥We first have a button that should not issue a request until an auth token has been retrieved:

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

接下来,我们将添加一些脚本来处理 auth promise(由库返回):

¥Next we will add some scripting to work with an auth promise (returned by a library):

<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 事件。

¥Here we use a global variable, but you could use localStorage or whatever preferred mechanism you want to communicate the authentication token to the htmx:configRequest event.

使用此代码后,htmx 将不会发出请求,直到 auth promise 得到解决。

¥With this code in place, htmx will not issue requests until the auth promise has been resolved.