Java Code Examples for org.springframework.web.socket.WebSocketSession#getPrincipal()
The following examples show how to use
org.springframework.web.socket.WebSocketSession#getPrincipal() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: StompSubProtocolHandler.java From spring4-understanding with Apache License 2.0 | 6 votes |
@SuppressWarnings("deprecation") private StompHeaderAccessor afterStompSessionConnected(Message<?> message, StompHeaderAccessor accessor, WebSocketSession session) { Principal principal = session.getPrincipal(); if (principal != null) { accessor = toMutableAccessor(accessor, message); accessor.setNativeHeader(CONNECTED_USER_HEADER, principal.getName()); if (this.userSessionRegistry != null) { String userName = getSessionRegistryUserName(principal); this.userSessionRegistry.registerSessionId(userName, session.getId()); } } long[] heartbeat = accessor.getHeartbeat(); if (heartbeat[1] > 0) { session = WebSocketSessionDecorator.unwrap(session); if (session instanceof SockJsSession) { ((SockJsSession) session).disableHeartbeat(); } } return accessor; }
Example 2
Source File: StompSubProtocolHandler.java From spring4-understanding with Apache License 2.0 | 6 votes |
@Override @SuppressWarnings("deprecation") public void afterSessionEnded(WebSocketSession session, CloseStatus closeStatus, MessageChannel outputChannel) { this.decoders.remove(session.getId()); Principal principal = session.getPrincipal(); if (principal != null && this.userSessionRegistry != null) { String userName = getSessionRegistryUserName(principal); this.userSessionRegistry.unregisterSessionId(userName, session.getId()); } Message<byte[]> message = createDisconnectMessage(session); SimpAttributes simpAttributes = SimpAttributes.fromMessage(message); try { SimpAttributesContextHolder.setAttributes(simpAttributes); if (this.eventPublisher != null) { Principal user = session.getPrincipal(); publishEvent(new SessionDisconnectEvent(this, message, session.getId(), closeStatus, user)); } outputChannel.send(message); } finally { SimpAttributesContextHolder.resetAttributes(); simpAttributes.sessionCompleted(); } }
Example 3
Source File: BasicAuthPrincipalHeadersCallback.java From spring-cloud-netflix-zuul-websocket with Apache License 2.0 | 5 votes |
@Override protected void applyHeadersInternal(WebSocketSession userAgentSession, WebSocketHttpHeaders headers) { Authentication authentication = (Authentication) userAgentSession.getPrincipal(); String usernameColonPwd = authentication.getName() + ":" + authentication.getCredentials().toString(); String encodedCredentials = new String( Base64.encode(usernameColonPwd.getBytes())); headers.put(HttpHeaders.AUTHORIZATION, Collections.singletonList("Basic " + encodedCredentials)); if (logger.isDebugEnabled()) { logger.debug("Added basic authentication header for user " + authentication.getName() + " to web sockets http headers"); } }
Example 4
Source File: OAuth2BearerPrincipalHeadersCallback.java From spring-cloud-netflix-zuul-websocket with Apache License 2.0 | 5 votes |
@Override protected void applyHeadersInternal(WebSocketSession userAgentSession, WebSocketHttpHeaders headers) { OAuth2Authentication oAuth2Authentication = (OAuth2Authentication) userAgentSession.getPrincipal(); OAuth2AuthenticationDetails details = (OAuth2AuthenticationDetails) oAuth2Authentication.getDetails(); String accessToken = details.getTokenValue(); headers.put(HttpHeaders.AUTHORIZATION, Collections.singletonList("Bearer " + accessToken)); if (logger.isDebugEnabled()) { logger.debug("Added Oauth2 bearer token authentication header for user " + oAuth2Authentication.getName() + " to web sockets http headers"); } }
Example 5
Source File: WebSocketRegistryListener.java From spring-session with Apache License 2.0 | 5 votes |
private void afterConnectionEstablished(WebSocketSession wsSession) { Principal principal = wsSession.getPrincipal(); if (principal == null) { return; } String httpSessionId = getHttpSessionId(wsSession); registerWsSession(httpSessionId, wsSession); }
Example 6
Source File: OfframpWebSocketHandler.java From data-highway with Apache License 2.0 | 4 votes |
@Override public void afterConnectionEstablished(WebSocketSession session) throws Exception { sessionId = session.getId(); Map<String, Object> attributes = session.getAttributes(); version = (String) attributes.get(VERSION); roadName = (String) attributes.get(ROAD_NAME); streamName = (String) attributes.get(STREAM_NAME); DefaultOffset defaultOffset = (DefaultOffset) attributes.get(DEFAULT_OFFSET); @SuppressWarnings("unchecked") Set<Sensitivity> grants = (Set<Sensitivity>) attributes.get(GRANTS); Authentication authentication = (Authentication) session.getPrincipal(); RoadConsumer consumer; metrics = metricsFactory.create(roadName, streamName); try { authorisation.checkAuthorisation(authentication, roadName, grants); consumer = consumerFactory.create(roadName, streamName, defaultOffset); MessageFunction messageFunction = messageFunctionFactory.create(roadName, grants); EventSender sender = bytes -> sendEvent(session, bytes); service = serviceFactory.create(version, consumer, messageFunction, sender, metrics); } catch (UnknownRoadException e) { metrics.markRoadNotFound(); session.close(); throw e; } Scheduler scheduler = Schedulers.newSingle( String.format("offramp[v%s,%s.%s:%s]", version, roadName, streamName, sessionId)); metrics.incrementActiveConnections(); Mono<Void> mono = Mono .fromRunnable(service) .subscribeOn(scheduler) .doOnError(t -> true, t -> { log.error("Road: {}, stream: {}, sessionId: {} - Error in OfframpService", roadName, streamName, sessionId, t); }) .doOnSuccess(s -> { log.info("Road: {}, stream: {}, sessionId: {} - OfframpService Completed", roadName, streamName, sessionId); }) .doOnTerminate(() -> { disposables.dispose(); metrics.decrementActiveConnections(); }).then(); disposables.add(() -> close(service)); disposables.add(() -> close(consumer)); disposables.add(() -> close(() -> session.close(SERVER_ERROR))); disposables.add(scheduler); disposables.add(mono.subscribe()); log.info("Road: {}, stream: {}, sessionId: {} - Connection established with defaultOffset: {}", roadName, streamName, sessionId, defaultOffset); metrics.markConnectionEstablished(); }
Example 7
Source File: StompSubProtocolHandler.java From spring-analysis-note with MIT License | 4 votes |
@Nullable private Principal getUser(WebSocketSession session) { Principal user = this.stompAuthentications.get(session.getId()); return (user != null ? user : session.getPrincipal()); }
Example 8
Source File: StompSubProtocolHandler.java From java-technology-stack with MIT License | 4 votes |
@Nullable private Principal getUser(WebSocketSession session) { Principal user = this.stompAuthentications.get(session.getId()); return (user != null ? user : session.getPrincipal()); }
Example 9
Source File: BasicAuthPrincipalHeadersCallback.java From spring-cloud-netflix-zuul-websocket with Apache License 2.0 | 4 votes |
@Override protected boolean shouldApplyHeaders(WebSocketSession userAgentSession, WebSocketHttpHeaders headers) { return !headers.containsKey(HttpHeaders.AUTHORIZATION) && userAgentSession.getPrincipal() instanceof Authentication; }
Example 10
Source File: OAuth2BearerPrincipalHeadersCallback.java From spring-cloud-netflix-zuul-websocket with Apache License 2.0 | 4 votes |
@Override protected boolean shouldApplyHeaders(WebSocketSession userAgentSession, WebSocketHttpHeaders headers) { return !headers.containsKey(HttpHeaders.AUTHORIZATION) && userAgentSession.getPrincipal() instanceof OAuth2Authentication; }
Example 11
Source File: StompSubProtocolHandler.java From spring4-understanding with Apache License 2.0 | 4 votes |
/** * Handle STOMP messages going back out to WebSocket clients. */ @Override @SuppressWarnings("unchecked") public void handleMessageToClient(WebSocketSession session, Message<?> message) { if (!(message.getPayload() instanceof byte[])) { logger.error("Expected byte[] payload. Ignoring " + message + "."); return; } StompHeaderAccessor stompAccessor = getStompHeaderAccessor(message); StompCommand command = stompAccessor.getCommand(); if (StompCommand.MESSAGE.equals(command)) { if (stompAccessor.getSubscriptionId() == null) { logger.warn("No STOMP \"subscription\" header in " + message); } String origDestination = stompAccessor.getFirstNativeHeader(SimpMessageHeaderAccessor.ORIGINAL_DESTINATION); if (origDestination != null) { stompAccessor = toMutableAccessor(stompAccessor, message); stompAccessor.removeNativeHeader(SimpMessageHeaderAccessor.ORIGINAL_DESTINATION); stompAccessor.setDestination(origDestination); } } else if (StompCommand.CONNECTED.equals(command)) { this.stats.incrementConnectedCount(); stompAccessor = afterStompSessionConnected(message, stompAccessor, session); if (this.eventPublisher != null && StompCommand.CONNECTED.equals(command)) { try { SimpAttributes simpAttributes = new SimpAttributes(session.getId(), session.getAttributes()); SimpAttributesContextHolder.setAttributes(simpAttributes); Principal user = session.getPrincipal(); publishEvent(new SessionConnectedEvent(this, (Message<byte[]>) message, user)); } finally { SimpAttributesContextHolder.resetAttributes(); } } } byte[] payload = (byte[]) message.getPayload(); if (StompCommand.ERROR.equals(command) && getErrorHandler() != null) { Message<byte[]> errorMessage = getErrorHandler().handleErrorMessageToClient((Message<byte[]>) message); stompAccessor = MessageHeaderAccessor.getAccessor(errorMessage, StompHeaderAccessor.class); Assert.notNull(stompAccessor, "Expected STOMP headers"); payload = errorMessage.getPayload(); } sendToClient(session, stompAccessor, payload); }
Example 12
Source File: WsTtyHandler.java From haven-platform with Apache License 2.0 | 4 votes |
private TempAuth withAuth(WebSocketSession session) { Authentication auth = (Authentication) session.getPrincipal(); return TempAuth.open(auth); }