在Elixir / Phoenix中处理无效令牌上的websocket连接

问题描述 投票:1回答:1

我们使用Guardian生成令牌,然后在连接到Phoenix Channels的套接字时用于身份验证。

最近我们发现有些用户从不离开某些页面,并且在一个月左右之后,令牌变为无效,这使Phoenix Channels连接尝试无效。

你如何在客户端处理此类案件?是否有一个特定的错误可以从凤凰城返回,让前端知道是什么原因?我们在connectuser_socket.ex函数看起来像这样:

def connect(%{"guardian_token" => token}, socket) do
  case Guardian.Phoenix.Socket.authenticate(socket, MyApp.Guardian, token) do
    {:ok, authed_socket} ->
      {:ok, authed_socket}

    {:error, _} ->
      :error
  end
end

有没有办法使用凤凰卫视频道的Phoenix JS库捕获此错误?我们的目标是1)如果令牌过期则停止重试,2)可能会注销用户或显示用户离线的消息。我们检查了Phoenix JS' documentation但找不到合适的东西。

elixir phoenix-framework phoenix-channels
1个回答
0
投票

您可以尝试使用每个连接或每当您认为合适时刷新令牌

也许这样的事情

# Refresh a token and set it on connect
def connect(%{"guardian_token" => token}, socket) do

  case MyApp.Guardian.refresh(token) do

    {:ok, _old_stuff, {new_token, new_claims}} -> 
      case Guardian.Phoenix.Socket.authenticate(socket, MyApp.Guardian, new_token, new_claims) do
        {:ok, authed_socket} ->
          {:ok, authed_socket}
        {:error, _} ->
          :socket_auth_failed
      end

    _ ->
      {:token_refresh_failed, "could not refresh token"}
  end
end

© www.soinside.com 2019 - 2024. All rights reserved.