@Override public void modifyHandshake(ServerEndpointConfig config, HandshakeRequest request, HandshakeResponse response) { HttpSession httpSession = (HttpSession) request.getHttpSession(); super.modifyHandshake(config, request, response); if (httpSession == null) { LOGGER.info("httpSession == null after modifyHandshake"); httpSession = (HttpSession) request.getHttpSession(); } if (httpSession == null) { LOGGER.info("httpSession == null"); return; } config.getUserProperties().put("httpSession", httpSession); httpSession = (HttpSession) request.getHttpSession(); LOGGER.info("modifyHandshake " + httpSession.getId()); }
@Override public void modifyHandshake(ServerEndpointConfig sec, HandshakeRequest request, HandshakeResponse response) { super.modifyHandshake(sec, request, response); if ( token == null || token.isEmpty() ) { Log.log(Level.FINEST, this, "No token set for room, skipping validation"); } else { Log.log(Level.FINEST, this, "Validating WS handshake"); SignedRequestHmac wsHmac = new SignedRequestHmac("", token, "", request.getRequestURI().getRawPath()); try { wsHmac.checkHeaders(new SignedRequestMap.MLS_StringMap(request.getHeaders())) .verifyFullSignature() .wsResignRequest(new SignedRequestMap.MLS_StringMap(response.getHeaders())); Log.log(Level.INFO, this, "validated and resigned", wsHmac); } catch(Exception e) { Log.log(Level.WARNING, this, "Failed to validate HMAC, unable to establish connection", e); response.getHeaders().replace(HandshakeResponse.SEC_WEBSOCKET_ACCEPT, Collections.emptyList()); } } }
@Override public void modifyHandshake(ServerEndpointConfig config, HandshakeRequest request, HandshakeResponse response) { Map<String, List<String>> headers = request.getHeaders(); if (headers != null && headers.containsKey(WatcherSecurityKey.HTTP_HEADER)) { List<String> header = headers.get(WatcherSecurityKey.HTTP_HEADER); if (header.size() > 0) { config.getUserProperties().put(WatcherSecurityKey.HTTP_HEADER, header. get(0)); } } HttpSession httpSession = (HttpSession) request.getHttpSession(); String user = request.getUserPrincipal().getName(); config.getUserProperties().put("httpSession", httpSession); config.getUserProperties().put("user", user); logger.log(Level.INFO, "Hand shake for upgrade to websocket by: {0}", user); }
/** * Intercept the handshake operation so that we can take a hold of the * ServletContext instance to be able to retrieve attributes stored to it * such as the database object and other similar class instances * <p/> * @param config * @param request * @param response */ @Override public void modifyHandshake(ServerEndpointConfig config, HandshakeRequest request, HandshakeResponse response) { HttpSession httpSession = (HttpSession) request.getHttpSession(); ServletContext context = (ServletContext) httpSession.getServletContext(); config.getUserProperties().put("httpSession", httpSession); config.getUserProperties().put("user", request.getUserPrincipal().getName()); /* * store these attributes to servletContext so that they are available to * every created user socket session */ config.getUserProperties().put("protocol", context.getAttribute("protocol")); }
/** * Test of handleOpenConnexion method, of class IWSControllerMonitor. * @throws java.lang.Exception */ @Test public void testHandleOpenConnexion() throws Exception { System.out.println("handleOpenConnexion"); Session session = mock(Session.class); EndpointConfig config = mock(EndpointConfig.class); HandshakeRequest handshakeRequest = mock(HandshakeRequest.class); HttpSession httpSession = mock(HttpSession.class); Map<String, Object> configProperties = mock(Map.class); when(config.getUserProperties()).thenReturn(configProperties); when(handshakeRequest.getHttpSession()).thenReturn(httpSession); when(httpSession.getId()).thenReturn("SESSIONID"); when(configProperties.get(eq(Constants.HANDSHAKEREQUEST))).thenReturn(handshakeRequest); instance.handleOpenConnexion(session, config); verify(httpSessionManager).addSession(eq(session), eq("SESSIONID")); verify(iwse).handleOpenConnexion(eq(session), eq(config)); }
/** * Return locale of client * * @param request * @return */ Locale getLocale(HandshakeRequest request) { if(null != request) { Map<String, List<String>> headers = request.getHeaders(); if(null != headers) { List<String> accepts = headers.get(HttpHeaders.ACCEPT_LANGUAGE); logger.debug("Get accept-language from client headers : {}", accepts); if (null != accepts) { for (String accept : accepts) { try { return localeExtractor.extractFromAccept(accept); } catch (LocaleNotFoundException ex) { } } } } } return Locale.US; }
/** * Test of handleOpenConnexion method, of class WSEndpoint. * * @throws java.io.IOException */ @Test public void testHandleOpenConnexionFromBrowser() throws IOException { System.out.println("handleOpenConnexion"); HandshakeRequest request = mock(HandshakeRequest.class); EndpointConfig config = mock(EndpointConfig.class); Map<String, Object> map = new HashMap<>(); map.put(Constants.HANDSHAKEREQUEST, request); Session session = mock(Session.class); when(config.getUserProperties()).thenReturn(map); when(session.getId()).thenReturn("WSSESSIONID"); doNothing().when(instance).setContext(eq(request)); instance.handleOpenConnexion(session, config); verify(userContextFactory).createUserContext(any(HandshakeRequest.class), eq("WSSESSIONID")); }
/** * Test of handleOpenConnexion method, of class IWSDecorator. * @throws java.lang.Exception */ @Test public void testHandleOpenConnexion() throws Exception { System.out.println("handleOpenConnexion"); Session session = mock(Session.class); EndpointConfig config = mock(EndpointConfig.class); Map map = mock(Map.class); HandshakeRequest request = mock(HandshakeRequest.class); HttpSession httpSession = mock(HttpSession.class); when(session.getId()).thenReturn("WSID"); when(config.getUserProperties()).thenReturn(map); when(map.get(eq(Constants.HANDSHAKEREQUEST))).thenReturn(request); when(request.getHttpSession()).thenReturn(httpSession); when(httpSession.getId()).thenReturn("HTTPID"); instance.handleOpenConnexion(session, config); verify(sessionManager).linkWsToHttp(eq(session), eq("HTTPID")); verify(iwse).handleOpenConnexion(eq(session), eq(config)); }
/** * Test of getPrincipal method, of class PrincipalTools. */ @Test public void testGetPrincipal_HandshakeRequest() { System.out.println("getPrincipal"); HandshakeRequest handshakeRequest = mock(HandshakeRequest.class); Principal principal = mock(Principal.class); when(principal.getName()).thenReturn("FOO"); when(handshakeRequest.getUserPrincipal()).thenReturn(null).thenReturn(principal); Principal result = instance.getPrincipal(handshakeRequest); assertThat(result).isNotNull(); assertThat(result.getName()).isEqualTo(Constants.ANONYMOUS); result = instance.getPrincipal(handshakeRequest); assertThat(result).isEqualTo(principal); assertThat(result.getName()).isEqualTo("FOO"); handshakeRequest = null; result = instance.getPrincipal(handshakeRequest); assertThat(result).isNotNull(); assertThat(result.getName()).isEqualTo(Constants.ANONYMOUS); }
/** * Test of getPrincipal method, of class WsUserContext. */ @Test public void testGetPrincipal() { System.out.println("getPrincipal"); Principal principal = mock(Principal.class); PrincipalTools principalTools = mock(PrincipalTools.class); HandshakeRequest handshakeRequest = mock(HandshakeRequest.class); when(principalTools.getPrincipal(eq(handshakeRequest))).thenReturn(principal); WsUserContext instance = new WsUserContext(handshakeRequest); instance.principalTools = principalTools; Principal result = instance.getPrincipal(); assertThat(result).isNotNull(); assertThat(result).isEqualTo(principal); }
@Override public Set<ServerEndpointConfig> getEndpointConfigs(Set<Class<? extends Endpoint>> set) { return new HashSet<ServerEndpointConfig>() {{ add(ServerEndpointConfig.Builder .create(MyEndpoint.class, "/websocket") .configurator(new ServerEndpointConfig.Configurator() { @Override public void modifyHandshake(ServerEndpointConfig sec, HandshakeRequest request, HandshakeResponse response) { HttpSession session = (HttpSession)request.getHttpSession(); System.out.println("HttpSession id: " + session.getId()); System.out.println("HttpSession creation time: " + session.getCreationTime()); super.modifyHandshake(sec, request, response); } }) .build()); }}; }
public void modifyHandshake(ServerEndpointConfig config, HandshakeRequest request, HandshakeResponse response) { HttpServletRequest _request = (HttpServletRequest) GenericReflection.NoThrow.getValue(_HandshakeRequest, request); Request _requestFaced = (Request) GenericReflection.NoThrow.getValue(Core.requestField, _request); MimeHeaders mime = new MimeHeaders(); Enumeration<String> enuns = _requestFaced.getHeaderNames(); while(enuns.hasMoreElements()){ String param = (String) enuns.nextElement(); mime.addValue(param).setString(_requestFaced.getHeader(param)); } Map<String, Object> properties = config.getUserProperties(); properties.put("httpRequest", _request); properties.put("httpResponse", _request.getAttribute("httpResponse")); properties.put("httpSession", _request.getSession()); properties.put("context", _requestFaced.getContext()); properties.put("headers", mime); properties.put("remoteHost", _request.getRemoteHost()); properties.put("localPort", _request.getLocalPort()); properties.put("remoteAddr", _request.getRemoteAddr()); }
@Override public String authenticate(HandshakeRequest request) throws AuthenticationException { SecurityContext context = SecurityContextHolder.getContext(); if (context == null) { throw new AuthenticationException("User not authenticateded", "Anonymous"); } Authentication authentication = context.getAuthentication(); if (authentication == null) { throw new AuthenticationException("User not authenticateded", "Anonymous"); } if (authentication.isAuthenticated()) { return authentication.getName(); } else { throw new AuthenticationException("User not authenticateded", authentication.getName()); } }
@Override public String authenticate(AuthenticationProvider provider, HandshakeRequest request) throws AuthenticationException { AuthenticationProvider auth = resolveAuthenticationProvider(provider); if (auth != null) { try { String username = auth.authenticate(request); fireAuthentication(username, request, null); return username; } catch(AuthenticationException ae) { LOG.warn("Unauthorized access by " + ae.getUsername() + " : " +ae.getMessage()); fireAuthentication(ae.getUsername(), request, ae); throw ae; } } return null; }
@Override public String getId(HandshakeRequest request, ClientChannel manager) { String clientId = getIdValue(request); if (manager.hasClient(clientId)) { clientId = clientId + "-" + getUuid(); } if (clientId == null) { clientId = getUuid(); } return clientId; }
@Override public void modifyHandshake(ServerEndpointConfig sec, HandshakeRequest request, HandshakeResponse response) { HttpSession httpSession = (HttpSession) request.getHttpSession(); sec.getUserProperties().put(HttpSession.class.getName(), httpSession); }
@Override public void modifyHandshake(ServerEndpointConfig config, HandshakeRequest request, HandshakeResponse response) { HttpSession httpSession = (HttpSession) request.getHttpSession(); if (null != httpSession) { config.getUserProperties().put(HttpSession.class.getName(), httpSession); } }
@Override public void modifyHandshake(ServerEndpointConfig sec, HandshakeRequest request, HandshakeResponse response) { System.out.println("modifyHandshake() Current thread " + Thread.currentThread().getName()); String user = request.getParameterMap().get("user").get(0); sec.getUserProperties().put(user, request.getHttpSession()); System.out.println("modifyHandshake() User " + user + " with http session ID " + ((HttpSession) request.getHttpSession()).getId()); }
@Override public void modifyHandshake(ServerEndpointConfig sec, HandshakeRequest request, HandshakeResponse response) { final HttpSession httpSession = (HttpSession) request.getHttpSession(); if (request.getUserPrincipal() == null) { return; } final SecurityContext securityCtx = new WebSocketSecurityContext(request); sec.getUserProperties().put(key(httpSession.getId()), securityCtx); }
@Override public void modifyHandshake(ServerEndpointConfig config, HandshakeRequest request, HandshakeResponse response) { super.modifyHandshake(config, request, response); // Store tunnel request and tunnel request service for retrieval // upon WebSocket open Map<String, Object> userProperties = config.getUserProperties(); userProperties.clear(); userProperties.put(TUNNEL_REQUEST_PROPERTY, new WebSocketTunnelRequest(request)); userProperties.put(TUNNEL_REQUEST_SERVICE_PROPERTY, tunnelRequestServiceProvider.get()); }
@Override public void modifyHandshake(final ServerEndpointConfig config, final HandshakeRequest request, final HandshakeResponse response) { final HttpSession httpSession = (HttpSession) request.getHttpSession(); config.getUserProperties().put(HttpSession.class.getName(), httpSession); }
@Override public void modifyHandshake(ServerEndpointConfig sec, HandshakeRequest request, HandshakeResponse response) { final Principal principal = request.getUserPrincipal(); final Subject subject = SecurityActions.getSubject(); final Object credential = SecurityActions.getCredential(); sec.getUserProperties().put(WebsocketSecurityInterceptor.SESSION_PRINCIPAL, principal); sec.getUserProperties().put(WebsocketSecurityInterceptor.SESSION_SUBJECT, subject); sec.getUserProperties().put(WebsocketSecurityInterceptor.SESSION_CREDENTIAL, credential); }
@Override public void modifyHandshake(ServerEndpointConfig config, HandshakeRequest request, HandshakeResponse response) { HttpSession session = (HttpSession) request.getHttpSession(); if (null != session) { config.getUserProperties().put("demo", 1L); } }
private Configurator createConfigurator() { return new Configurator() { @Override public void modifyHandshake( ServerEndpointConfig sec, HandshakeRequest request, HandshakeResponse response) { super.modifyHandshake(sec, request, response); final HttpSession httpSession = (HttpSession) request.getHttpSession(); if (httpSession != null) { sec.getUserProperties().put(HTTP_SESSION_ATTRIBUTE, httpSession); } sec.getUserProperties().put(SECURITY_CONTEXT, createSecurityContext(request)); sec.getUserProperties().put(ENVIRONMENT_CONTEXT, EnvironmentContext.getCurrent()); } }; }
protected SecurityContext createSecurityContext(final HandshakeRequest req) { final boolean isSecure = false; // todo: get somehow from request final String authType = "BASIC"; final Subject subject = EnvironmentContext.getCurrent().getSubject(); final Principal principal = new SimplePrincipal(subject.getUserName()); return new SecurityContext() { @Override public Principal getUserPrincipal() { return principal; } @Override public boolean isUserInRole(String role) { return false; } @Override public boolean isSecure() { return isSecure; } @Override public String getAuthenticationScheme() { return authType; } }; }
private ServerEndpointConfig.Configurator configuratorFor(final String prefix, final boolean isRaw) { return new ServerEndpointConfig.Configurator() { @Override public <T> T getEndpointInstance(Class<T> endpointClass) throws InstantiationException { try { return endpointClass.getConstructor(SockJsServer.class, String.class, String.class) .newInstance(sockJsServer, context.getContextPath(), prefix); } catch (Exception e) { throw new RuntimeException(e); } } @Override public void modifyHandshake(ServerEndpointConfig sec, HandshakeRequest request, HandshakeResponse response) { if (isRaw) { // We have no reliable key (like session id) to save // headers with for raw websocket requests return; } String path = request.getRequestURI().getPath(); Matcher matcher = SESSION_PATTERN.matcher(path); if (matcher.matches()) { String sessionId = matcher.group(1); saveHeaders(sessionId, request.getHeaders()); } } }; }
@Override public void modifyHandshake(ServerEndpointConfig config, HandshakeRequest request, HandshakeResponse response) { HttpSession httpSession = (HttpSession) request.getHttpSession(); config.getUserProperties() .put(HttpSession.class.getName(), httpSession); }
private ServerEndpointConfig.Configurator configuratorFor(final String prefix, final boolean isRaw) { return new ServerEndpointConfig.Configurator() { @Override public <T> T getEndpointInstance(Class<T> endpointClass) throws InstantiationException { try { return endpointClass.getConstructor(SockJsServer.class, String.class, String.class) .newInstance(sockJsServer, getServletContext().getContextPath(), prefix); } catch (Exception e) { throw new RuntimeException(e); } } @Override public void modifyHandshake(ServerEndpointConfig sec, HandshakeRequest request, HandshakeResponse response) { if (isRaw) { // We have no reliable key (like session id) to save // headers with for raw websocket requests return; } String path = request.getRequestURI().getPath(); Matcher matcher = SESSION_PATTERN.matcher(path); if (matcher.matches()) { String sessionId = matcher.group(1); saveHeaders(sessionId, request.getHeaders()); } } }; }
public static final RequestAgent getWsRequestAgent(HandshakeRequest request, HandshakeResponse response) { // this is an abstraction point. this class can be loaded from configuration. if (request instanceof HttpServletRequest) { return new RequestAgent.HTTP((HttpServletRequest) request, (HttpServletResponse) response); } else { return null; } }
@Override public void handleOpenConnexion(Session session, EndpointConfig config) throws IOException { logger.debug("Decorate websocket, open connexion '{}'", session.getId()); Map<String, Object> configProperties = config.getUserProperties(); HandshakeRequest request = (HandshakeRequest) configProperties.get(Constants.HANDSHAKEREQUEST); httpSessionManager.addSession(session, ((HttpSession) request.getHttpSession()).getId()); iwse.handleOpenConnexion(session, config); }
public Principal getPrincipal(HandshakeRequest handshakeRequest) { if (null != handshakeRequest && handshakeRequest.getUserPrincipal() != null) { return handshakeRequest.getUserPrincipal(); } else { return ANONYMOUS; } }
@Override public void handleOpenConnexion(Session session, EndpointConfig config) throws IOException { logger.debug("Decorate websocket, open connexion '{}'", session.getId()); Map<String, Object> configProperties = config.getUserProperties(); HandshakeRequest request = (HandshakeRequest) configProperties.get(Constants.HANDSHAKEREQUEST); sessionManager.linkWsToHttp(session, ((HttpSession) request.getHttpSession()).getId()); iwse.handleOpenConnexion(session, config); }
@Override public void handleOpenConnexion(Session session, EndpointConfig config) throws IOException { logger.debug("Open connexion for session '{}'", session.getId()); Map<String, Object> configProperties = config.getUserProperties(); // Get infos from config and set in session, only one time by connexion HandshakeRequest request = (HandshakeRequest) configProperties.get(Constants.HANDSHAKEREQUEST); setContext(request); userContextFactory.createUserContext(request, session.getId()); }
/** * * @param request */ void setContext(HandshakeRequest request) { HttpSession httpSession = (HttpSession) request.getHttpSession(); ThreadLocalContextHolder.put(Constants.HTTPSESSION, httpSession); if(null == httpSession.getAttribute(Constants.LOCALE)) { httpSession.setAttribute(Constants.LOCALE, getLocale(request)); } }
public void createUserContext(HandshakeRequest request, String wsid) { if (request != null) { if (wsid != null) { map.put(wsid, new WsUserContext(request)); } } else { destroyUserContext(wsid); } }
/** * Test of setContext method, of class. */ @Test public void setContextTest() { System.out.println("setContext"); ThreadLocalContextHolder.cleanupThread(); HandshakeRequest request = mock(HandshakeRequest.class); HttpSession httpSession = mock(HttpSession.class); when(request.getHttpSession()).thenReturn(httpSession); when(httpSession.getAttribute(eq(Constants.LOCALE))).thenReturn(null).thenReturn(Locale.CHINA); doReturn(Locale.CANADA).when(instance).getLocale(eq(request)); instance.setContext(request); Object result = ThreadLocalContextHolder.get(Constants.HTTPSESSION); verify(httpSession).setAttribute(eq(Constants.LOCALE), eq(Locale.CANADA)); assertThat(result).isEqualTo(httpSession); }
/** * Test of getLocale method, of class RSEndpoint. * @throws org.ocelotds.exceptions.LocaleNotFoundException */ @Test public void testGetLocaleNotFound() throws LocaleNotFoundException { Locale result = instance.getLocale(null); assertThat(result).isEqualTo(Locale.US); HandshakeRequest request = mock(HandshakeRequest.class); when(request.getHeaders()).thenReturn(null); result = instance.getLocale(request); assertThat(result).isEqualTo(Locale.US); Map<String, List<String>> headers = new HashMap<>(); when(request.getHeaders()).thenReturn(headers); assertThat(result).isEqualTo(Locale.US); }
/** * Test of getLocale method, of class RSEndpoint. * @throws org.ocelotds.exceptions.LocaleNotFoundException */ @Test public void testGetLocale() throws LocaleNotFoundException { System.out.println("getLocale"); HandshakeRequest request = mock(HandshakeRequest.class); Map<String, List<String>> headers = new HashMap<>(); when(request.getHeaders()).thenReturn(headers); when(localeExtractor.extractFromAccept(any(String.class))).thenThrow(LocaleNotFoundException.class).thenReturn(Locale.FRANCE).thenReturn(Locale.CHINA); headers.put(HttpHeaders.ACCEPT_LANGUAGE, Arrays.asList(null, "acceptFrance", "acceptChina")); Locale result = instance.getLocale(request); assertThat(result).isEqualTo(Locale.FRANCE); }
/** * Test of isUserInRole method, of class WsUserContext. */ @Test public void testIsUserInRole() { System.out.println("isUserInRole"); HandshakeRequest handshakeRequest = mock(HandshakeRequest.class); when(handshakeRequest.isUserInRole(eq("OK"))).thenReturn(true); when(handshakeRequest.isUserInRole(eq("NOK"))).thenReturn(false); WsUserContext instance = new WsUserContext(handshakeRequest); boolean result = instance.isUserInRole("OK"); assertThat(result).isTrue(); result = instance.isUserInRole("NOK"); assertThat(result).isFalse(); }
/** * Test of modifyHandshake method, of class OcelotRequestConfigurator. */ @Test public void testModifyHandshake() { System.out.println("testModifyHandshake"); ServerEndpointConfig sec = mock(ServerEndpointConfig.class); Map<String, Object> userProperties = new HashMap<>(); HandshakeRequest request = mock(HandshakeRequest.class); HandshakeResponse response = mock(HandshakeResponse.class); when(sec.getUserProperties()).thenReturn(userProperties); instance.modifyHandshake(sec, request, response); assertThat(userProperties.get(Constants.HANDSHAKEREQUEST)).isEqualTo(request); }