通过openresty使用密钥斗篷对Websocket进行身份验证

时间:2019-03-06 16:23:30

标签: nginx websocket keycloak openresty lua-resty-openidc

目前,我有一个包含以下组件的有效解决方案:

  • 具有自定义应用程序的Web服务器
  • 带有lua的Openresty
  • 钥匙斗篷

这使我可以使用密钥斗篷进行身份验证。
因为我的Web服务器还公开了一个Websocket主机,所以我也想对这些Websocket进行身份验证。有没有人有一个示例(nginx文件和lua文件都可用)来使用openresty验证websocket连接?我看过https://github.com/openresty/lua-resty-websocket,但似乎找不到在身份验证部分中插入的位置。
一个示例客户端应用程序来测试这一点也很好!

1 个答案:

答案 0 :(得分:1)

我自己弄清楚了。在此处发布我的解决方案以帮助其他人实现同样的目标。
我有以下代码片段:

Openresty配置

仅用于websocket,应放置在服务器部分内:

set $resty_user 'not_authenticated_resty_user';
location /ws {
      access_by_lua_file         /usr/local/openresty/nginx/conf/lua_access.lua;
      proxy_pass                    http://<backend-websocket-host>/ws;
      proxy_http_version            1.1;
      proxy_set_header              Host                $http_host;
      proxy_set_header              X-Real-IP           $remote_addr;
      proxy_set_header              X-Forwarded-For     $proxy_add_x_forwarded_for;

      proxy_set_header              Upgrade             $http_upgrade;
      proxy_set_header              Connection          "upgrade";
      proxy_set_header              X-Forwared-User     $resty_user;
      proxy_read_timeout            1d;
      proxy_send_timeout            1d;
    }

lua_acces.lua

local opts = {
    redirect_uri = "/*",
    discovery = "http://<keycloak-url>/auth/realms/realm/.well-known/openid-configuration",
    client_id = "<client-id>",
    client_secret = "<client-secret>",
    redirect_uri_scheme = "https",
    logout_path = "/logout",
    redirect_after_logout_uri = "http://<keycloak-url>/auth/realms/realm/protocol/openid-connect/logout?redirect_uri=http%3A%2F%2google.com",
    redirect_after_logout_with_id_token_hint = false,
    session_contents = {id_token=true},
    ssl_verify=no
  }

  -- call introspect for OAuth 2.0 Bearer Access Token validation
  local res, err = require("resty.openidc").bearer_jwt_verify(opts)
  if err or not res then
    print("Token authentication not succeeded")
    if err then
      print("jwt_verify error message:")
      print(err)
    end
    if res then
      print("jwt_verify response:")
      tprint(res)
    end
    res, err = require("resty.openidc").authenticate(opts)
    if err then
      ngx.status = 403
      ngx.say(err)
      ngx.exit(ngx.HTTP_FORBIDDEN)
    end
  end

if res.id_token and res.id_token.preferred_username then
    ngx.var.resty_user = res.id_token.preferred_username
  else
    ngx.var.resty_user = res.preferred_username
  end

仅当Websocket连接具有从密钥斗篷服务中检索到的有效令牌时,才允许它们。
最后,resty用户被填充以将经过身份验证的用户传递给后端应用程序。

示例Java客户端应用程序

获取密钥斗篷令牌

package test;

import org.keycloak.admin.client.Keycloak;
import org.keycloak.representations.AccessTokenResponse;

public class KeycloakConnection {
    private Keycloak _keycloak;

    public KeycloakConnection(final String host, String username, String password, String clientSecret, String realm, String clientId) {

        _keycloak = Keycloak.getInstance(
                "http://" + host + "/auth",
                realm,
                username,
                password,
                clientId,
                clientSecret);
    }

    public String GetAccessToken()
    {
        final AccessTokenResponse accessToken = _keycloak.tokenManager().getAccessToken();
        return accessToken.getToken();
    }
}

Websocket

此代码段仅包含我调用的用于设置websocket连接的功能。您仍然必须实例化_keycloakConnection对象,在我的情况下,我有一个通用的_session字段,以便每次需要时都可以重用该会话。

private Session GetWebsocketSession(String host)
    {
        URI uri = URI.create("wss://" + host);
        ClientUpgradeRequest request = new ClientUpgradeRequest();
        request.setHeader("Authorization", "Bearer " + _keycloakConnection.GetAccessToken());
        _client = new WebSocketClient();
        try {
                _client.start();
                // The socket that receives events
                WebsocketEventHandler socketEventHandler = new WebsocketEventHandler(this::NewLiveMessageReceivedInternal);
                // Attempt Connect
                Future<Session> fut = _client.connect(socketEventHandler, uri, request);
                // Wait for Connect
                _session = fut.get();

                return _session;
        } catch (Throwable t) {
            _logger.error("Error during websocket session creation", t);
        }
        return null;
    }

WebsocketEventHandler

在此类中注入了一个使用者,以在另一个类别中使用消息

package test;

import org.apache.log4j.Logger;
import org.eclipse.jetty.websocket.api.Session;
import org.eclipse.jetty.websocket.api.WebSocketAdapter;

import java.util.function.Consumer;

public class WebsocketEventHandler extends WebSocketAdapter
{
    private final Logger _logger;
    private Consumer<String> _onMessage;

    public WebsocketEventHandler(Consumer<String> onMessage) {
        _onMessage = onMessage;
        _logger = Logger.getLogger(WebsocketEventHandler.class);
    }

    @Override
    public void onWebSocketConnect(Session sess)
    {
        super.onWebSocketConnect(sess);
        _logger.info("Socket Connected: " + sess);
    }

    @Override
    public void onWebSocketText(String message)
    {
        super.onWebSocketText(message);
        _logger.info("Received TEXT message: " + message);
        _onMessage.accept(message);
    }

    @Override
    public void onWebSocketClose(int statusCode, String reason)
    {
        super.onWebSocketClose(statusCode,reason);
        _logger.info("Socket Closed: [" + statusCode + "] " + reason);
    }

    @Override
    public void onWebSocketError(Throwable cause)
    {
        super.onWebSocketError(cause);
        _logger.error("Websocket error", cause);
    }
}

发送消息

创建_session时,您可以使用以下行发送数据:

_session.getRemote().sendString("Hello world");

这些摘录只是我整个解决方案的一小部分。我可能错过了一些东西。如果有人有问题或无法解决您的问题,请与我们联系,我们将提供更多信息。