Search in sources :

Example 66 with Principal

use of java.security.Principal in project spring-framework by spring-projects.

the class UndertowRequestUpgradeStrategy method upgrade.

@Override
public Mono<Void> upgrade(ServerWebExchange exchange, WebSocketHandler handler, Optional<String> subProtocol) {
    ServerHttpRequest request = exchange.getRequest();
    Assert.isInstanceOf(UndertowServerHttpRequest.class, request, "UndertowServerHttpRequest required");
    HttpServerExchange httpExchange = ((UndertowServerHttpRequest) request).getUndertowExchange();
    Set<String> protocols = subProtocol.map(Collections::singleton).orElse(Collections.emptySet());
    Hybi13Handshake handshake = new Hybi13Handshake(protocols, false);
    List<Handshake> handshakes = Collections.singletonList(handshake);
    URI url = request.getURI();
    HttpHeaders headers = request.getHeaders();
    Mono<Principal> principal = exchange.getPrincipal();
    HandshakeInfo info = new HandshakeInfo(url, headers, principal, subProtocol);
    DataBufferFactory bufferFactory = exchange.getResponse().bufferFactory();
    try {
        DefaultCallback callback = new DefaultCallback(info, handler, bufferFactory);
        new WebSocketProtocolHandshakeHandler(handshakes, callback).handleRequest(httpExchange);
    } catch (Exception ex) {
        return Mono.error(ex);
    }
    return Mono.empty();
}
Also used : HttpHeaders(org.springframework.http.HttpHeaders) Hybi13Handshake(io.undertow.websockets.core.protocol.version13.Hybi13Handshake) ServerHttpRequest(org.springframework.http.server.reactive.ServerHttpRequest) UndertowServerHttpRequest(org.springframework.http.server.reactive.UndertowServerHttpRequest) URI(java.net.URI) HttpServerExchange(io.undertow.server.HttpServerExchange) WebSocketProtocolHandshakeHandler(io.undertow.websockets.WebSocketProtocolHandshakeHandler) DataBufferFactory(org.springframework.core.io.buffer.DataBufferFactory) UndertowServerHttpRequest(org.springframework.http.server.reactive.UndertowServerHttpRequest) Principal(java.security.Principal) HandshakeInfo(org.springframework.web.reactive.socket.HandshakeInfo) Hybi13Handshake(io.undertow.websockets.core.protocol.version13.Hybi13Handshake) Handshake(io.undertow.websockets.core.protocol.Handshake)

Example 67 with Principal

use of java.security.Principal in project spring-framework by spring-projects.

the class StompSubProtocolHandler method handleMessageFromClient.

/**
	 * Handle incoming WebSocket messages from clients.
	 */
public void handleMessageFromClient(WebSocketSession session, WebSocketMessage<?> webSocketMessage, MessageChannel outputChannel) {
    List<Message<byte[]>> messages;
    try {
        ByteBuffer byteBuffer;
        if (webSocketMessage instanceof TextMessage) {
            byteBuffer = ByteBuffer.wrap(((TextMessage) webSocketMessage).asBytes());
        } else if (webSocketMessage instanceof BinaryMessage) {
            byteBuffer = ((BinaryMessage) webSocketMessage).getPayload();
        } else {
            return;
        }
        BufferingStompDecoder decoder = this.decoders.get(session.getId());
        if (decoder == null) {
            throw new IllegalStateException("No decoder for session id '" + session.getId() + "'");
        }
        messages = decoder.decode(byteBuffer);
        if (messages.isEmpty()) {
            if (logger.isTraceEnabled()) {
                logger.trace("Incomplete STOMP frame content received in session " + session + ", bufferSize=" + decoder.getBufferSize() + ", bufferSizeLimit=" + decoder.getBufferSizeLimit() + ".");
            }
            return;
        }
    } catch (Throwable ex) {
        if (logger.isErrorEnabled()) {
            logger.error("Failed to parse " + webSocketMessage + " in session " + session.getId() + ". Sending STOMP ERROR to client.", ex);
        }
        handleError(session, ex, null);
        return;
    }
    for (Message<byte[]> message : messages) {
        try {
            StompHeaderAccessor headerAccessor = MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class);
            headerAccessor.setSessionId(session.getId());
            headerAccessor.setSessionAttributes(session.getAttributes());
            headerAccessor.setUser(getUser(session));
            headerAccessor.setHeader(SimpMessageHeaderAccessor.HEART_BEAT_HEADER, headerAccessor.getHeartbeat());
            if (!detectImmutableMessageInterceptor(outputChannel)) {
                headerAccessor.setImmutable();
            }
            if (logger.isTraceEnabled()) {
                logger.trace("From client: " + headerAccessor.getShortLogMessage(message.getPayload()));
            }
            boolean isConnect = StompCommand.CONNECT.equals(headerAccessor.getCommand());
            if (isConnect) {
                this.stats.incrementConnectCount();
            } else if (StompCommand.DISCONNECT.equals(headerAccessor.getCommand())) {
                this.stats.incrementDisconnectCount();
            }
            try {
                SimpAttributesContextHolder.setAttributesFromMessage(message);
                boolean sent = outputChannel.send(message);
                if (sent) {
                    if (isConnect) {
                        Principal user = headerAccessor.getUser();
                        if (user != null && user != session.getPrincipal()) {
                            this.stompAuthentications.put(session.getId(), user);
                        }
                    }
                    if (this.eventPublisher != null) {
                        if (isConnect) {
                            publishEvent(new SessionConnectEvent(this, message, getUser(session)));
                        } else if (StompCommand.SUBSCRIBE.equals(headerAccessor.getCommand())) {
                            publishEvent(new SessionSubscribeEvent(this, message, getUser(session)));
                        } else if (StompCommand.UNSUBSCRIBE.equals(headerAccessor.getCommand())) {
                            publishEvent(new SessionUnsubscribeEvent(this, message, getUser(session)));
                        }
                    }
                }
            } finally {
                SimpAttributesContextHolder.resetAttributes();
            }
        } catch (Throwable ex) {
            if (logger.isErrorEnabled()) {
                logger.error("Failed to send client message to application via MessageChannel" + " in session " + session.getId() + ". Sending STOMP ERROR to client.", ex);
            }
            handleError(session, ex, message);
        }
    }
}
Also used : TextMessage(org.springframework.web.socket.TextMessage) Message(org.springframework.messaging.Message) WebSocketMessage(org.springframework.web.socket.WebSocketMessage) BinaryMessage(org.springframework.web.socket.BinaryMessage) StompHeaderAccessor(org.springframework.messaging.simp.stomp.StompHeaderAccessor) ByteBuffer(java.nio.ByteBuffer) BinaryMessage(org.springframework.web.socket.BinaryMessage) BufferingStompDecoder(org.springframework.messaging.simp.stomp.BufferingStompDecoder) TextMessage(org.springframework.web.socket.TextMessage) Principal(java.security.Principal)

Example 68 with Principal

use of java.security.Principal in project spring-framework by spring-projects.

the class StompSubProtocolHandlerTests method handleMessageFromClientWithTokenAuthentication.

// SPR-14690
@Test
public void handleMessageFromClientWithTokenAuthentication() {
    ExecutorSubscribableChannel channel = new ExecutorSubscribableChannel();
    channel.addInterceptor(new AuthenticationInterceptor("__pete__@gmail.com"));
    channel.addInterceptor(new ImmutableMessageChannelInterceptor());
    TestMessageHandler messageHandler = new TestMessageHandler();
    channel.subscribe(messageHandler);
    StompSubProtocolHandler handler = new StompSubProtocolHandler();
    handler.afterSessionStarted(this.session, channel);
    TextMessage wsMessage = StompTextMessageBuilder.create(StompCommand.CONNECT).build();
    handler.handleMessageFromClient(this.session, wsMessage, channel);
    assertEquals(1, messageHandler.getMessages().size());
    Message<?> message = messageHandler.getMessages().get(0);
    Principal user = SimpMessageHeaderAccessor.getUser(message.getHeaders());
    assertNotNull(user);
    assertEquals("__pete__@gmail.com", user.getName());
}
Also used : ExecutorSubscribableChannel(org.springframework.messaging.support.ExecutorSubscribableChannel) ImmutableMessageChannelInterceptor(org.springframework.messaging.support.ImmutableMessageChannelInterceptor) TextMessage(org.springframework.web.socket.TextMessage) Principal(java.security.Principal) TestPrincipal(org.springframework.messaging.simp.TestPrincipal) Test(org.junit.Test)

Example 69 with Principal

use of java.security.Principal in project platform_frameworks_base by android.

the class WiFiKeyManager method chooseClientAlias.

@Override
public String chooseClientAlias(String[] keyTypes, Principal[] issuers, Socket socket) {
    Map<String, Integer> keyPrefs = new HashMap<>(keyTypes.length);
    int pref = 0;
    for (String keyType : keyTypes) {
        keyPrefs.put(keyType, pref++);
    }
    List<AliasEntry> aliases = new ArrayList<>();
    if (issuers != null) {
        for (Principal issuer : issuers) {
            if (issuer instanceof X500Principal) {
                String[] aliasAndKey = mAliases.get((X500Principal) issuer);
                if (aliasAndKey != null) {
                    Integer preference = keyPrefs.get(aliasAndKey[1]);
                    if (preference != null) {
                        aliases.add(new AliasEntry(preference, aliasAndKey[0]));
                    }
                }
            }
        }
    } else {
        for (String[] aliasAndKey : mAliases.values()) {
            Integer preference = keyPrefs.get(aliasAndKey[1]);
            if (preference != null) {
                aliases.add(new AliasEntry(preference, aliasAndKey[0]));
            }
        }
    }
    Collections.sort(aliases);
    return aliases.isEmpty() ? null : aliases.get(0).getAlias();
}
Also used : HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) X500Principal(javax.security.auth.x500.X500Principal) X500Principal(javax.security.auth.x500.X500Principal) Principal(java.security.Principal)

Example 70 with Principal

use of java.security.Principal in project jstorm by alibaba.

the class SingleUserSimpleTransport method getDefaultSubject.

@Override
protected Subject getDefaultSubject() {
    HashSet<Principal> principals = new HashSet<Principal>();
    principals.add(new Principal() {

        public String getName() {
            return "user";
        }

        public String toString() {
            return "user";
        }
    });
    return new Subject(true, principals, new HashSet<Object>(), new HashSet<Object>());
}
Also used : Principal(java.security.Principal) Subject(javax.security.auth.Subject) HashSet(java.util.HashSet)

Aggregations

Principal (java.security.Principal)931 Test (org.junit.Test)243 Subject (javax.security.auth.Subject)114 EveryonePrincipal (org.apache.jackrabbit.oak.spi.security.principal.EveryonePrincipal)114 HashSet (java.util.HashSet)89 User (org.apache.jackrabbit.api.security.user.User)75 Group (org.apache.jackrabbit.api.security.user.Group)74 Authorizable (org.apache.jackrabbit.api.security.user.Authorizable)58 Privilege (javax.jcr.security.Privilege)57 RepositoryException (javax.jcr.RepositoryException)51 IOException (java.io.IOException)50 ArrayList (java.util.ArrayList)48 HttpServletRequest (javax.servlet.http.HttpServletRequest)47 TestPrincipal (org.apache.jackrabbit.core.security.TestPrincipal)45 AbstractSecurityTest (org.apache.jackrabbit.oak.AbstractSecurityTest)43 EveryonePrincipal (org.apache.jackrabbit.core.security.principal.EveryonePrincipal)42 PrincipalIterator (org.apache.jackrabbit.api.security.principal.PrincipalIterator)40 HashMap (java.util.HashMap)39 PrincipalImpl (org.apache.jackrabbit.oak.spi.security.principal.PrincipalImpl)39 X500Principal (javax.security.auth.x500.X500Principal)38