@Override
  public Object createWebSocket(final JettyServerUpgradeRequest request, final JettyServerUpgradeResponse response) {
    try {
      Optional<WebSocketAuthenticator<T>> authenticator = Optional.ofNullable(environment.getAuthenticator());

      final ReusableAuth<T> authenticated;
      if (authenticator.isPresent()) {
        authenticated = authenticator.get().authenticate(request);

        if (authenticated.invalidCredentialsProvided()) {
          response.sendForbidden("Unauthorized");
          return null;
        }
      } else {
        authenticated = ReusableAuth.anonymous();
      }

      return new WebSocketResourceProvider<>(getRemoteAddress(request),
          remoteAddressPropertyName,
          this.jerseyApplicationHandler,
          this.environment.getRequestLog(),
          authenticated,
          this.environment.getMessageFactory(),
          ofNullable(this.environment.getConnectListener()),
          this.environment.getIdleTimeout());
    } catch (AuthenticationException | IOException e) {
      logger.warn("Authentication failure", e);
      try {
        response.sendError(500, "Failure");
      } catch (IOException ignored) {
      }
      return null;
    }
  }
@Test
  void testValidAuthorization() throws AuthenticationException {
    Account account = new Account();

    when(environment.getAuthenticator()).thenReturn(authenticator);
    when(authenticator.authenticate(eq(request)))
        .thenReturn(ReusableAuth.authenticated(account, PrincipalSupplier.forImmutablePrincipal()));
    when(environment.jersey()).thenReturn(jerseyEnvironment);
    final HttpServletRequest httpServletRequest = mock(HttpServletRequest.class);
    when(httpServletRequest.getAttribute(REMOTE_ADDRESS_PROPERTY_NAME)).thenReturn("127.0.0.1");
    when(request.getHttpServletRequest()).thenReturn(httpServletRequest);

    WebSocketResourceProviderFactory<?> factory = new WebSocketResourceProviderFactory<>(environment, Account.class,
        mock(WebSocketConfiguration.class), REMOTE_ADDRESS_PROPERTY_NAME);
    Object connection = factory.createWebSocket(request, response);

    assertNotNull(connection);
    verifyNoMoreInteractions(response);
    verify(authenticator).authenticate(eq(request));

    ((WebSocketResourceProvider<?>) connection).onWebSocketConnect(mock(Session.class));

    assertNotNull(((WebSocketResourceProvider<?>) connection).getContext().getAuthenticated());
    assertEquals(((WebSocketResourceProvider<?>) connection).getContext().getAuthenticated(), account);
  }