SSL Websocket using StompClient -- SSL Certificate exception

I have simple Java StompClient connecting to Java websocket events. It works when server is configured as ws. Not able to connect when server is configured as wss. Code snippted below...

KeyStore truststore = KeyStore.getInstance("JKS");
truststore.load(this.getClass().getResourceAsStream("/truststore.jks"), "<hidden_pwd_for_thispost>".toCharArray());
KeyStore keystore = KeyStore.getInstance("JKS");;
keystore.load(this.getClass().getResourceAsStream("/keystore.jks"), "<hidden_pwd_for_thispost>".toCharArray());

SSLContext sslContext = new 
SSLContextBuilder().loadTrustMaterial(truststore, acceptingTrustStrategy);
            .loadKeyMaterial(keystore, "<hidden_pwd_forthisPost>".toCharArray()).build();
TrustStrategy acceptingTrustStrategy = (X509Certificate[] chain, String authType) -> true;
StandardWebSocketClient client = new StandardWebSocketClient();
client.getUserProperties().clear();
client.getUserProperties().put("org.apache.tomcat.websocket.SSL_CONTEXT", sslContext);
WebSocketStompClient stompClient = new WebSocketStompClient(client);   
ListenableFuture<StompSession> sessionFuture = stompClient.connect(url, handler);
session = sessionFuture.get();

Exception

Caused by: java.security.cert.CertificateException: No name matching <myhost> found
at sun.security.util.HostnameChecker.matchDNS(Unknown Source)
at sun.security.util.HostnameChecker.match(Unknown Source)
at sun.security.ssl.X509TrustManagerImpl.checkIdentity(Unknown Source)
at sun.security.ssl.AbstractTrustManagerWrapper.checkAdditionalTrust(Unknown Source)
at sun.security.ssl.AbstractTrustManagerWrapper.checkServerTrusted(Unknown Source)

Please note I have build keyStore and selfSigned trustStore locally. Anf both keyStore and trustStore has CN as my hostname. Verified above by running keytool -list

Can some please suggest. Your help much appreciated.

Apologies if this question is already answered, i have searched for while with no result. Hence posting.

Thanks,

2 answers

  • answered 2018-10-18 11:21 Ankur Chrungoo

    Does the Subject Alternative Name in your certificate match the Server Host name?

    X509v3 extensions:
        X509v3 Subject Alternative Name:
            DNS:<**HOST name which matches the server host name**>
    

    You can check this by using below steps:

    •   openssl s_client -connect <serverhostname>:<port on which you connect>
    •   Copy the string from -----BEGIN CERTIFICATE-----  till     -----END CERTIFICATE-----
    •   Paste the string into a .pem file, for example:- “test.pem”
    •   Run command:   openssl x509 -in test.pem -noout -text
    

    If SAN doesn't have the host name, then DN comes into picture: Refer this:- CertificateException: No name matching ssl.someUrl.de found


    UPDATE:

    If you are trying to achieve mutual authentication, that means both the server and the client should have their own certificate. Based on the code _stompClient.connect(url, handler); it seems to me that the Websocket server called by StompClient is acting as the server here, and your calling code is the client. Based on this understanding, you must configure your certificates correctly. I think you need to provide more details to the question to clarify how you have set things up. SSL is a complex topic, even a slight mistake in configuration can result in an error.(evident from the fact that WS is working but not WSS)


    UPDATE:

    Based on your updated comment, it means that client certificate is not in picture, so no mutual authentication, but only server certificate will be used by the client, and it will check if it trusts the server certificate which means the CA which signs the server certificate should be present in the client's trust store. If your server is accessible as a web-server you could try opening it via the browser and checking if it shows a valid certificate if you use https to access any resource/UI. That should at-least help in figuring out whether the certificate is properly configured or not.

  • answered 2018-10-18 14:57 Prashanth G

    Issue is Resolved.....Please check comments

  • The internal of hot reloading

    I have been using webpack hot reload in development and it is awesome. It saves me a lot of time. I have been searching over the web today to get a good grasp of how it actually works and have not found any good explanation about the internal working of it. So, I am asking here to get a good understanding of how it actually works.

    I have come a bit in my mini hot reload project. For now, I have set up a node server and a simple client side Javascript code. The client is connected to the server via websocket and the server fires change events to client based on fs.watch function from node.jsthat watched my code folder for every file change.

    I am stuck at how I can patch the update I recieve from server in client code. Right now, I have just index.js file in index.html. So I am wondering how bundling tools like webpack achieves hot reload, specifically how they patch the update.

    I've read from webpack docs that they have a thin hrm runtime in client code that update the patch, but I could not seem to find any detailed info on how they achieve this feat. Do they open the client index.js file using FileReader, read the file and write(?) back? Again, I do not have a clear understanding of how this works. So, if you guys could give me some direction, I could dig deeper into it.

    So my question is, how do they patch(insert) the new code into the already existing client code which resides in index.js?

  • Create certificate and CSR using Windows PowerShell/.Net without using external programs or libraries

    I would like to create a Private Key and a CSR, submit the CSR to a Certificate Authority, retrieve the certificate once issued, and have the Private Key and Certificate as separate PEM files suitable for use in non-Microsoft applications (they are generally web servers). I'd like to avoid using Java Keytool or OpenSSL to generate keys and certificate signing requests in Windows PowerShell on Windows Server 2016. The CSRs will be submitted to a Microsoft Active Directory Certificate Services.

    OpenSSL and Java are not (and won't be) installed on the computers requiring certificates. As the certificates are for non-Microsoft applications, I also want to avoid using the Certificate Store on the computers. I don't mind using "certreq" to actually submit the completed CSR and retrieve the resulting certificate once approved.

    I have some code, based on C# Export Private/Public RSA key from RSACryptoServiceProvider to PEM string, which will extract the private key from an X509Certificate2. So far, as an experiment, I have used this successfully with a PKCS12 keystore (where the key and CSR were created with Keytool).

    Inspired by Automate the process of creating a private key, a CSR and a final Signed Certificate in .NET Core I knocked together the following, but ran out of inspiration, and didn't really know what I was doing. How do I complete the process of submitting the CSR to the CA (or outputting the CSR as a file for using with certreq)?

    [int]$KeyLength = 2048
    $ComputerName = "jon"
    $Domain = "domain.local"
    [string]$DistinguishedName = "CN=$($ComputerName).$($Domain),OU=Unit,O=Org,C=GB"
    $HashAlgo = [System.Security.Cryptography.HashAlgorithmName]::SHA256
    $RSASigPadding = [System.Security.Cryptography.RSASignaturePadding]::Pkcs1
    
    $RSAKey = [System.Security.Cryptography.RSA]::Create($KeyLength)
    $Certificate = [System.Security.Cryptography.X509Certificates.CertificateRequest]::new($DistinguishedName,$RSAKey,$HashAlgo,$RSASigPadding)
    
    # Add Basic Constraints
    $BasicConstraints = [System.Security.Cryptography.X509Certificates.X509BasicConstraintsExtension]::new($false,$false,0,$false)
    $BCExtension = [System.Security.Cryptography.X509Certificates.X509Extension]::new($BasicConstraints,$false)
    $Certificate.CertificateExtensions.Add($BCExtension)
    
    # Add Subject Key Identifier extension
    $SubjectKeyIdentifier = [System.Security.Cryptography.X509Certificates.X509SubjectKeyIdentifierExtension]::new($Certificate.PublicKey,$false)
    $SKIExtension = [System.Security.Cryptography.X509Certificates.X509Extension]::new($SubjectKeyIdentifier,$false)
    $Certificate.CertificateExtensions.Add($SKIExtension)
    
    # Add Key Usage
    $KeyUsageFlags = [System.Security.Cryptography.X509Certificates.X509KeyUsageFlags]::DigitalSignature -bor [System.Security.Cryptography.X509Certificates.X509KeyUsageFlags]::KeyEncipherment
    $KeyUsage = [System.Security.Cryptography.X509Certificates.X509KeyUsageExtension]::new($KeyUsageFlags,$true)
    $KUExtension = [System.Security.Cryptography.X509Certificates.X509Extension]::new($KeyUsage,$true)
    $Certificate.CertificateExtensions.Add($KUExtension)
    
    # Add EKU
    $ServerAuthentication = [System.Security.Cryptography.Oid]::New("Server Authentication")
    $EKUOidCollection = [System.Security.Cryptography.OidCollection]::new()
    $EKUOidCollection.Add($ServerAuthentication) | out-null # this outputs 0
    $EnhancedKeyUsage = [System.Security.Cryptography.X509Certificates.X509EnhancedKeyUsageExtension]::new($EKUOidCollection,$false)
    $EKUExtension = [System.Security.Cryptography.X509Certificates.X509Extension]::new($EnhancedKeyUsage,$false)
    $Certificate.CertificateExtensions.Add($EKUExtension)
    
    # Add SAN
    $SubjectAlternateNameBuilder = [System.Security.Cryptography.X509Certificates.SubjectAlternativeNameBuilder]::new()
    $SubjectAlternateNameBuilder.AddDnsName("$($ComputerName).$($Domain)")
    $Certificate.CertificateExtensions.Add($SubjectAlternateNameBuilder.Build())
    
  • Weird SSL common name mismatch

    Today I came across a weird case of cn mismatch. I have two domains:

    kpmg.talentsource.rs and www.kpmg.talentsource.rs

    both have prod.q.ssl.global.fastly.net as their CNAME they have the same A records and certificates.

    Nevertheless:

    https://kpmg.talentsource.rs (OK)

    https://www.kpmg.talentsource.rs (CN mismatch)


    https://www.ssllabs.com/ssltest/analyze.html?d=kpmg.talentsource.rs&s=151.101.65.62 https://www.ssllabs.com/ssltest/analyze.html?d=www.kpmg.talentsource.rs&s=151.101.65.62

    Note: none of the two has the kpmg.talentsource.rs in neither the the CN nor the SAN

    Any ideas why this is happening?

  • ERR_CONNECTION_REFUSED when redirecting http to https using nodejs

    I'm trying to redirect http requests to https using nodejs. Here is my code so far. I have included all key, certs etc. http and https ports are ON ( custom ports, not defaults)

    Now on hitting http, site does get redirected to https but it shows err as shown in screenshot attached. screenshot.

    certs are valid ( see bottom of screenshot ) but still it says THIS PAGE IS NOT SECURE.

    Please guide me where i'm wrong and possible solution.

    I have searched here but couldn't get solution to this. Thanks.

       var fs = require('fs');
    var http = require('http');
    var http_port    =any_port; 
    var app = require('express')();
    
    // HTTPS definitions
    var https = require('https');
    var https_port    =another_port; 
    var options = {
        key: fs.readFileSync('example.key'),
        cert:fs.readFileSync('example.crt'),
        ca:  fs.readFileSync('bundleexample.crt')
    };
    
    app.get('/', function (req, res) {
       res.end('Hello https World!');
    });
    
    https.createServer(options, app).listen(https_port, function () {
       console.log('https port ' + https_port); 
    });
    
    // Redirect from http port to https
    
    http.createServer(function (req, res) {
        res.writeHead(301, { "Location": "https://" + req.headers['host'].replace(http_port,https_port) + req.url });
        res.end();
    }).listen(http_port);
    
  • Error while compiling the angular project
    [ERROR in ./node_modules/stompjs/lib/stomp-node.js Module not found: Error: Can't resolve 'net' in 'C:\ANGULAR\websocket-example\node_modules\stompjs\lib'][1]
    

    added stompjs to angular by npm install stompjs --save

    imported into component.ts import * as Stomp from 'stompjs';

    and got error when using like this let socket = new WebSocket("ws://localhost:8080/greeting"); let ws = Stomp.over(socket);

  • Spring WebSocket Stomp Exception Handling

    I am trying to use Websockets and STOMP 1.2. I want to authenticate user using JWT on CONNECT frame and to return error message if authorization is not valid. Here is channel interceptor

    @Configuration
    @EnableWebSocketMessageBroker
    public class WebSocketConfig implements WebSocketMessageBrokerConfigurer
    {
        // ... Removed for readability
    
        @Override
        public void configureClientInboundChannel(ChannelRegistration registration)
        {
            registration.interceptors(new ChannelInterceptor()
            {
                @Override
                public Message<?> preSend(Message<?> message, MessageChannel channel)
                {
                    StompHeaderAccessor accessor =
                            MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class);
    
                    if (accessor != null && StompCommand.CONNECT.equals(accessor.getCommand()))
                    {
                        String token = accessor.getFirstNativeHeader(authorizationHeader);
                        if (token != null)
                        {
                            Authentication authentication = tokenUtil.getAuthentication(resolveToken(token));
                            accessor.setUser(authentication);
                        }
                        else
                        {
                            throw new UnauthorizedException();
                        }
                    }
                    return message;
                }
            });
    
        }
    }
    

    This way the error stack will have

        Failed to send client message to application via MessageChannel in session a63cf95f-4a5b-ef34-b74b-3264ec6dd61f. Sending STOMP ERROR to client.
    
    org.springframework.messaging.MessageDeliveryException: Failed to send message to ExecutorSubscribableChannel[clientInboundChannel]; nested exception is com.example.error.exception.UnauthorizedException: You are not authorized. Please log in.
        at org.springframework.messaging.support.AbstractMessageChannel.send(AbstractMessageChannel.java:146) ~[spring-messaging-5.1.2.RELEASE.jar:5.1.2.RELEASE]
        at org.springframework.messaging.support.AbstractMessageChannel.send(AbstractMessageChannel.java:122) ~[spring-messaging-5.1.2.RELEASE.jar:5.1.2.RELEASE]
        at org.springframework.web.socket.messaging.StompSubProtocolHandler.handleMessageFromClient(StompSubProtocolHandler.java:284) ~[spring-websocket-5.1.2.RELEASE.jar:5.1.2.RELEASE]
        at org.springframework.web.socket.messaging.SubProtocolWebSocketHandler.handleMessage(SubProtocolWebSocketHandler.java:324) [spring-websocket-5.1.2.RELEASE.jar:5.1.2.RELEASE]
        at org.springframework.web.socket.handler.WebSocketHandlerDecorator.handleMessage(WebSocketHandlerDecorator.java:75) [spring-websocket-5.1.2.RELEASE.jar:5.1.2.RELEASE]
        at org.springframework.web.socket.handler.LoggingWebSocketHandlerDecorator.handleMessage(LoggingWebSocketHandlerDecorator.java:56) [spring-websocket-5.1.2.RELEASE.jar:5.1.2.RELEASE]
        at org.springframework.web.socket.handler.ExceptionWebSocketHandlerDecorator.handleMessage(ExceptionWebSocketHandlerDecorator.java:58) [spring-websocket-5.1.2.RELEASE.jar:5.1.2.RELEASE]
        at org.springframework.web.socket.adapter.standard.StandardWebSocketHandlerAdapter.handleTextMessage(StandardWebSocketHandlerAdapter.java:113) [spring-websocket-5.1.2.RELEASE.jar:5.1.2.RELEASE]
        at org.springframework.web.socket.adapter.standard.StandardWebSocketHandlerAdapter.access$000(StandardWebSocketHandlerAdapter.java:42) [spring-websocket-5.1.2.RELEASE.jar:5.1.2.RELEASE]
        at org.springframework.web.socket.adapter.standard.StandardWebSocketHandlerAdapter$3.onMessage(StandardWebSocketHandlerAdapter.java:84) [spring-websocket-5.1.2.RELEASE.jar:5.1.2.RELEASE]
        at org.springframework.web.socket.adapter.standard.StandardWebSocketHandlerAdapter$3.onMessage(StandardWebSocketHandlerAdapter.java:81) [spring-websocket-5.1.2.RELEASE.jar:5.1.2.RELEASE]
        at org.apache.tomcat.websocket.WsFrameBase.sendMessageText(WsFrameBase.java:395) [tomcat-embed-websocket-9.0.12.jar:9.0.12]
        at org.apache.tomcat.websocket.server.WsFrameServer.sendMessageText(WsFrameServer.java:119) [tomcat-embed-websocket-9.0.12.jar:9.0.12]
        at org.apache.tomcat.websocket.WsFrameBase.processDataText(WsFrameBase.java:495) [tomcat-embed-websocket-9.0.12.jar:9.0.12]
        at org.apache.tomcat.websocket.WsFrameBase.processData(WsFrameBase.java:294) [tomcat-embed-websocket-9.0.12.jar:9.0.12]
        at org.apache.tomcat.websocket.WsFrameBase.processInputBuffer(WsFrameBase.java:133) [tomcat-embed-websocket-9.0.12.jar:9.0.12]
        at org.apache.tomcat.websocket.server.WsFrameServer.onDataAvailable(WsFrameServer.java:82) [tomcat-embed-websocket-9.0.12.jar:9.0.12]
        at org.apache.tomcat.websocket.server.WsFrameServer.doOnDataAvailable(WsFrameServer.java:171) [tomcat-embed-websocket-9.0.12.jar:9.0.12]
        at org.apache.tomcat.websocket.server.WsFrameServer.notifyDataAvailable(WsFrameServer.java:151) [tomcat-embed-websocket-9.0.12.jar:9.0.12]
        at org.apache.tomcat.websocket.server.WsHttpUpgradeHandler.upgradeDispatch(WsHttpUpgradeHandler.java:148) [tomcat-embed-websocket-9.0.12.jar:9.0.12]
        at org.apache.coyote.http11.upgrade.UpgradeProcessorInternal.dispatch(UpgradeProcessorInternal.java:54) [tomcat-embed-core-9.0.12.jar:9.0.12]
        at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:53) [tomcat-embed-core-9.0.12.jar:9.0.12]
        at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:770) [tomcat-embed-core-9.0.12.jar:9.0.12]
        at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1415) [tomcat-embed-core-9.0.12.jar:9.0.12]
        at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-embed-core-9.0.12.jar:9.0.12]
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) [na:1.8.0_131]
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) [na:1.8.0_131]
        at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core-9.0.12.jar:9.0.12]
        at java.lang.Thread.run(Thread.java:748) [na:1.8.0_131]
    Caused by: com.example.error.exception.UnauthorizedException: You are not authorized. Please log in.
        at com.exampleconfig.WebSocketConfig$1.preSend(WebSocketConfig.java:74) ~[classes/:na]
        at org.springframework.messaging.support.AbstractMessageChannel$ChannelInterceptorChain.applyPreSend(AbstractMessageChannel.java:178) ~[spring-messaging-5.1.2.RELEASE.jar:5.1.2.RELEASE]
        at org.springframework.messaging.support.AbstractMessageChannel.send(AbstractMessageChannel.java:132) ~[spring-messaging-5.1.2.RELEASE.jar:5.1.2.RELEASE]
        ... 28 common frames omitted
    

    And similar error will be sent to client end connection will be closed. But after the connection is closed, other stack trace is written as output:

    2018-11-11 01:06:48.077 DEBUG 7259 --- [nio-8080-exec-2] s.w.s.h.LoggingWebSocketHandlerDecorator : StandardWebSocketSession[id=a63cf95f-4a5b-ef34-b74b-3264ec6dd61f, uri=/api/ws] closed with CloseStatus[code=1000, reason=null]
    2018-11-11 01:06:48.077 DEBUG 7259 --- [nio-8080-exec-2] o.s.w.s.m.SubProtocolWebSocketHandler    : Clearing session a63cf95f-4a5b-ef34-b74b-3264ec6dd61f
    2018-11-11 01:06:48.084 DEBUG 7259 --- [nio-8080-exec-2] org.springframework.web.SimpLogging      : Detected unsent DISCONNECT message. Processing anyway.
    2018-11-11 01:06:48.085 DEBUG 7259 --- [nio-8080-exec-2] org.springframework.web.SimpLogging      : Processing DISCONNECT session=a63cf95f-4a5b-ef34-b74b-3264ec6dd61f
    2018-11-11 01:06:48.086 DEBUG 7259 --- [tboundChannel-1] o.s.w.s.m.SubProtocolWebSocketHandler    : No session for GenericMessage [payload=byte[0], headers={simpMessageType=DISCONNECT_ACK, simpDisconnectMessage=GenericMessage [payload=byte[0], headers={simpMessageType=DISCONNECT, stompCommand=DISCONNECT, simpSessionAttributes={org.springframework.messaging.simp.SimpAttributes.COMPLETED=true}, simpSessionId=a63cf95f-4a5b-ef34-b74b-3264ec6dd61f}], simpSessionId=a63cf95f-4a5b-ef34-b74b-3264ec6dd61f}]
    2018-11-11 01:06:48.087  WARN 7259 --- [nio-8080-exec-2] w.s.h.ExceptionWebSocketHandlerDecorator : Unhandled exception after connection closed for ExceptionWebSocketHandlerDecorator [delegate=LoggingWebSocketHandlerDecorator [delegate=SubProtocolWebSocketHandler[StompSubProtocolHandler[v10.stomp, v11.stomp, v12.stomp]]]]
    
    org.springframework.messaging.MessageDeliveryException: Failed to send message to ExecutorSubscribableChannel[clientInboundChannel]; nested exception is org.springframework.security.access.AccessDeniedException: Access is denied
        at org.springframework.messaging.support.AbstractMessageChannel.send(AbstractMessageChannel.java:146) ~[spring-messaging-5.1.2.RELEASE.jar:5.1.2.RELEASE]
        at org.springframework.messaging.support.AbstractMessageChannel.send(AbstractMessageChannel.java:122) ~[spring-messaging-5.1.2.RELEASE.jar:5.1.2.RELEASE]
        at org.springframework.web.socket.messaging.StompSubProtocolHandler.afterSessionEnded(StompSubProtocolHandler.java:611) ~[spring-websocket-5.1.2.RELEASE.jar:5.1.2.RELEASE]
        at org.springframework.web.socket.messaging.SubProtocolWebSocketHandler.clearSession(SubProtocolWebSocketHandler.java:516) ~[spring-websocket-5.1.2.RELEASE.jar:5.1.2.RELEASE]
        at org.springframework.web.socket.messaging.SubProtocolWebSocketHandler.afterConnectionClosed(SubProtocolWebSocketHandler.java:385) ~[spring-websocket-5.1.2.RELEASE.jar:5.1.2.RELEASE]
        at org.springframework.web.socket.handler.WebSocketHandlerDecorator.afterConnectionClosed(WebSocketHandlerDecorator.java:85) ~[spring-websocket-5.1.2.RELEASE.jar:5.1.2.RELEASE]
        at org.springframework.web.socket.handler.LoggingWebSocketHandlerDecorator.afterConnectionClosed(LoggingWebSocketHandlerDecorator.java:72) ~[spring-websocket-5.1.2.RELEASE.jar:5.1.2.RELEASE]
        at org.springframework.web.socket.handler.ExceptionWebSocketHandlerDecorator.afterConnectionClosed(ExceptionWebSocketHandlerDecorator.java:78) ~[spring-websocket-5.1.2.RELEASE.jar:5.1.2.RELEASE]
        at org.springframework.web.socket.adapter.standard.StandardWebSocketHandlerAdapter.onClose(StandardWebSocketHandlerAdapter.java:144) [spring-websocket-5.1.2.RELEASE.jar:5.1.2.RELEASE]
        at org.apache.tomcat.websocket.WsSession.fireEndpointOnClose(WsSession.java:535) [tomcat-embed-websocket-9.0.12.jar:9.0.12]
        at org.apache.tomcat.websocket.WsSession.onClose(WsSession.java:513) [tomcat-embed-websocket-9.0.12.jar:9.0.12]
        at org.apache.tomcat.websocket.WsFrameBase.processDataControl(WsFrameBase.java:347) [tomcat-embed-websocket-9.0.12.jar:9.0.12]
        at org.apache.tomcat.websocket.WsFrameBase.processData(WsFrameBase.java:289) [tomcat-embed-websocket-9.0.12.jar:9.0.12]
        at org.apache.tomcat.websocket.WsFrameBase.processInputBuffer(WsFrameBase.java:133) [tomcat-embed-websocket-9.0.12.jar:9.0.12]
        at org.apache.tomcat.websocket.server.WsFrameServer.onDataAvailable(WsFrameServer.java:82) [tomcat-embed-websocket-9.0.12.jar:9.0.12]
        at org.apache.tomcat.websocket.server.WsFrameServer.doOnDataAvailable(WsFrameServer.java:171) [tomcat-embed-websocket-9.0.12.jar:9.0.12]
        at org.apache.tomcat.websocket.server.WsFrameServer.notifyDataAvailable(WsFrameServer.java:151) [tomcat-embed-websocket-9.0.12.jar:9.0.12]
        at org.apache.tomcat.websocket.server.WsHttpUpgradeHandler.upgradeDispatch(WsHttpUpgradeHandler.java:148) [tomcat-embed-websocket-9.0.12.jar:9.0.12]
        at org.apache.coyote.http11.upgrade.UpgradeProcessorInternal.dispatch(UpgradeProcessorInternal.java:54) [tomcat-embed-core-9.0.12.jar:9.0.12]
        at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:53) [tomcat-embed-core-9.0.12.jar:9.0.12]
        at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:770) [tomcat-embed-core-9.0.12.jar:9.0.12]
        at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1415) [tomcat-embed-core-9.0.12.jar:9.0.12]
        at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-embed-core-9.0.12.jar:9.0.12]
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) [na:1.8.0_131]
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) [na:1.8.0_131]
        at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core-9.0.12.jar:9.0.12]
        at java.lang.Thread.run(Thread.java:748) [na:1.8.0_131]
    Caused by: org.springframework.security.access.AccessDeniedException: Access is denied
        at org.springframework.security.access.vote.AffirmativeBased.decide(AffirmativeBased.java:84) ~[spring-security-core-5.1.1.RELEASE.jar:5.1.1.RELEASE]
        at org.springframework.security.access.intercept.AbstractSecurityInterceptor.beforeInvocation(AbstractSecurityInterceptor.java:233) ~[spring-security-core-5.1.1.RELEASE.jar:5.1.1.RELEASE]
        at org.springframework.security.messaging.access.intercept.ChannelSecurityInterceptor.preSend(ChannelSecurityInterceptor.java:69) ~[spring-security-messaging-5.1.1.RELEASE.jar:5.1.1.RELEASE]
        at org.springframework.messaging.support.AbstractMessageChannel$ChannelInterceptorChain.applyPreSend(AbstractMessageChannel.java:178) ~[spring-messaging-5.1.2.RELEASE.jar:5.1.2.RELEASE]
        at org.springframework.messaging.support.AbstractMessageChannel.send(AbstractMessageChannel.java:132) ~[spring-messaging-5.1.2.RELEASE.jar:5.1.2.RELEASE]
        ... 26 common frames omitted
    

    I have no idea where AccessDeniedException came from and how can I handle this.

    If I do not throw UnauthorizedException in preSend method, client will be connected and when it tries to send something, it will receive AccessDeniedException, because all endpoints needs authenticated user, and then connection will be closed and stack trace for AccessDeniedException printed few times.

    What am I doing incorrect here and what is the correct way to handle this kind of use case?

  • Spring Boot 2 with WebSockets and StompJS handleFrame not called (Integration Testing)

    Hope someone can help with this, I'm pulling - what's left - of my hair out.

    Running a spring boot 2 application with OAuth security enabled. All of that appears to be working fine except for the fact that when I come to write an integration test for it I can't get the frameHandler to fire.

    I can confirm however that connecting to this client using a StompJS (JS) works fine and messages are received no problem.

    I've put the demo code proving the issue on github https://github.com/Curtis004/web-socket-client-issue/ - I've moved relevant code from my original project in order to reduce the number of moving parts and I'm still facing the same issue.. which is good.

    EDIT: Also tried removing withSockJS from the endpoint registration and using a plain old StandardWebSocketClient for the stomp client and got the same thing.